【Java】图片或文件上传下载


前言

在开发过程中,经常会有通过调用后端接口地址,则直接返回文件或者图片的需求,本篇文章用于参考示例我在开发过程中使用的代码;


一、图片上传

其他不用说,直接上代码:

    /**
     * 图片上传
     *
     * @param file 图片
     * @return JSON
     */
    (value = "/uplloadSystemPictures")
    public JSONObject uplloadSystemPictures((value = "file", required = false) MultipartFile file) {
    
    
        File targetFile;
        Object url = null;//返回存储路径
        String fileName = file.getOriginalFilename();//获取文件名加后缀
        if (fileName != null && !"".equals(fileName)) {
    
    
            //获取文件存储路径,这里也可以写死,我是存在配置中的;
            String path = wccs.findValueByName(PropertiesReader.getString("ICON_IMAGE_URL")); //文件存储位置
            log.info("文件存储位置 == {}", path);
            String fileF = fileName.substring(fileName.lastIndexOf("."));//文件后缀
            fileName = UUID.randomUUID().toString() + fileF;//新的文件名
            log.info("文件名称 == {}", fileName);
            //获取文件夹路径
            File file1 = new File(path);
            //将图片存入文件夹
            targetFile = new File(file1, fileName);
            //将上传的文件写到服务器上指定的文件。
            try {
    
    
                file.transferTo(targetFile);
            } catch (IOException e) {
    
    
                log.error("文件上传至服务器异常 == {}", e.getMessage());
                e.printStackTrace();
            }
            //我这里是获取系统配置的域名+下方的读取的接口名称,然后再加上文件名称;上传成功后,就返回这个地址给前端,前端就能调用了;
            url = wccs.findValueByName(PropertiesReader.getString("ICON_READ_IMAGE_URL")) + fileName;
        }
        return ResJsonUtil.toJsonSuccess(url);
    }

二、图片读取、下载

代码如下:

    /**
     * 读取图片
     * 请求地址中的fileName也就是文件名称以及文件格式了,例如:http://localhost:5780/getImage/355548sd.png 这种格式调用接口;根据传入的文件名称,去获取对应的文件;名称是通过上传的接口获取的哈,请看上一步
     * @param fileName 图片名称
     * @param response response
     */
    (value = "/getImage/{fileName:.+}")
    (value = "*", allowCredentials = "true")
    public void getImage( String fileName, HttpServletResponse response) {
    
    
        FileInputStream fis = null;
        try {
    
    
            OutputStream out = response.getOutputStream();
            //获取配置中的图片地址
            String addRess = wccs.findValueByName(PropertiesReader.getString("ICON_IMAGE_URL")) + "\\" + fileName;
            log.info("获取到的文件名称 == {}", fileName);
            File file = new File(addRess);
            fis = new FileInputStream(file);
            byte[] b = new byte[fis.available()];
            fis.read(b);
            out.write(b);
            out.flush();
        } catch (Exception e) {
    
    
            log.error("读取图片失败异常 == {}", e.getMessage());
        } finally {
    
    
            if (fis != null) {
    
    
                try {
    
    
                    fis.close();
                } catch (IOException io) {
    
    
                    log.error("返回图片关闭流异常 == {}", io.getMessage());
                }
            }
        }
    }

总结

功能很简单,就这一点代码;自己写的话可以优化下代码,我这老项目,以前写的就无所谓了;只是方便展示;

猜你喜欢

转载自blog.csdn.net/qq_42666609/article/details/132079115