java 上传图片至本地 并读取图片在网页中显示

java 上传图片至本地 并读取图片在网页中显示
代码+图片如下所示
一、代码

@Controller
public class ImageController {
    private static Logger logger = LoggerFactory.getLogger(ImageController.class);
    @Autowired
    private ImageService imageService;


    @ResponseBody
    @RequestMapping(value="uploadImage", method = RequestMethod.POST, produces = "application/json;charset=utf-8")
    public void uploadImage(@RequestParam("file") MultipartFile[] files){
        for (int i = 0; i < files.length; i++) {
            MultipartFile file = files[i];
            if (!file.isEmpty()) {
                imageService.imageService(file);
            }
        }
    }

    @ResponseBody
    @RequestMapping(value = "/getImage", method = RequestMethod.GET, produces = "application/json;charset=utf-8")
    public void getImage(String filename, HttpServletResponse response){
        imageService.getImage(filename,response);
    }
}
@Service
public class ImageService {
    /*
        getOriginalFilename:获取上传时的文件名
        getName:获取表单中文件组件的名字
     */

    //将文件写入到本地
    public void imageService(MultipartFile file){
        FileOutputStream out = null;
        try {
            byte[] bytes = file.getBytes();
            String path = "C:\\Users\\Desktop\\pitcture\\"+file.getOriginalFilename();
            File newFile = new File(path);
            out = new FileOutputStream(newFile);
            out.write(bytes);
            out.flush();
            System.out.println("成功保存至本地");
        } catch (IOException e) {
            e.printStackTrace();
        } finally {
            try {
                out.close();
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
    }

    //从本地读取文件并返回到网页中
    public void getImage(String filename, HttpServletResponse response){
        FileInputStream in = null;
        ServletOutputStream out = null;
        try {
            File file = new File("C:\\Users\\Desktop\\pitcture\\"+filename);
            in = new FileInputStream(file);
            out = response.getOutputStream();
            byte[] bytes = new byte[1024 * 10];
            int len = 0;
            while ((len = in.read(bytes)) != -1) {
                out.write(bytes,0,len);
            }
            out.flush();
        } catch (IOException e) {
            e.printStackTrace();
        } finally {
            try {
                in.close();
                out.close();
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
    }
}

二、图片
使用postman进行接口测试
这里写图片描述

这里写图片描述

猜你喜欢

转载自blog.csdn.net/qq_32657967/article/details/81543195
今日推荐