spring boot 中图片的上传与访问路径设置,文件的上传与下载

图片上传示例:

@Slf4j
public class ImageUpload {

    public void saveImage(String base64Url) throws BusinessException {
        MultipartFile multipartFile = null;
        try {
            String[] baseStrs = base64Url.split(",");
            byte[] b = new byte[0];
            b = Base64.decodeBase64(baseStrs[1]);
            for (int i = 0; i < b.length; ++i) {
                if (b[i] < 0) {//调整异常数据
                    b[i] += 256;
                }
            }
            multipartFile = new BASE64DecodedMultipartFile(b, baseStrs[0]);
            //设置图片存储路径
            File imagePath = new File("E:/images/meeting/file");
            if (!imagePath.exists()) {
                imagePath.mkdirs();
            }
            String name = UUID.randomUUID().toString().replaceAll("-", "").toUpperCase();
            File imageFile = new File(imagePath, name);
            if (imageFile.exists()) {
                imageFile.delete();
            }
            multipartFile.transferTo(imageFile);
        } catch (Exception e) {
            log.info(e.getMessage());
            e.printStackTrace();
        }
    }
}

在application.properties中设置图片访问的路径:

spring.mvc.static-path-pattern=http://ip:post/images/**
spring.resources.static-locations=file:图片真正存储的路径filepath

 文件上传示例:

配置文件上传的大小:spring.servlet.multipart.maxFileSize=2MB

编码:

spring.http.encoding.charset=UTF-8
spring.http.encoding.enabled=true
spring.http.encoding.force=true
public boolean getSuffixs(String suffixName) {
    String suffix = ".doc/.docx/.pdf";
    HashSet suffixs = new HashSet();
    String[] strs = suffix.split("/");
    for (String str : strs) {
        if (!suffixs.contains(str)) {
            suffixs.add(str);
        }
    }
    if (!suffixs.contains(suffixName)) {
        return false;
    }
    return true;
}
public String fileUpload(@RequestParam("file") MultipartFile file) {
    String filePath = "E:/images/meeting/file/";
    try {
        if (file.isEmpty()) {
            return "文件为空";
        }
        // 获取文件名
        String fileName = new String(file.getOriginalFilename());
        log.info("上传的文件名为:" + fileName);
        // 获取文件的后缀名
        String suffixName = fileName.substring(fileName.lastIndexOf("."));
        log.info("文件的后缀名为:" + suffixName);
        String str = ".doc/.docx/.pdf";
        if (!getSuffixs(suffixName)) {
            return "文件格式不正确,允许上传的文件格式有:";
        }
        // 设置文件存储路径
        String name = UUID.randomUUID().toString().replaceAll("-", "").toUpperCase();
        String path = filePath+ name;
        File dest = new File(path, fileName);
        // 检测是否存在目录
        if (!dest.getParentFile().exists()) {
            dest.getParentFile().mkdirs();// 新建文件夹
        }
        file.transferTo(dest);// 文件写入
        String fileDownLoadPath = "http://localhost:8080/file/download/" + name + "/" + fileName;
        return fileDownLoadPath;
    } catch (IllegalStateException e) {
        e.printStackTrace();
    } catch (IOException e) {
        e.printStackTrace();
    }
    return "文件上传失败";
}

文件下载示例:

public String downloadFile(@PathVariable String path, @PathVariable String fileName, HttpServletRequest request,
    HttpServletResponse response) {
    String filePath = "E:/images/meeting/file/";
    // 设置文件名,根据业务需要替换成要下载的文件名
    if (fileName != null) {
        //设置文件路径
        String realPath = filePath + path;
        File file = new File(realPath, fileName);
        //用于解决下载下来的文件名乱码问题
        String userAgent = request.getHeader("User-Agent");
        try {
            if (userAgent.contains("MSIE") || userAgent.contains("Trident")) {
                fileName = java.net.URLEncoder.encode(fileName, "UTF-8");
            } else {
                fileName = new String(fileName.getBytes("UTF-8"), "ISO-8859-1");
            }
        } catch (UnsupportedEncodingException e) {
            e.printStackTrace();
        }
        if (file.exists()) {
            response.setContentType("application/force-download");// 设置强制下载不打开
            response.addHeader("Content-Disposition", "attachment;fileName=" + fileName);// 设置文件名
            byte[] buffer = new byte[1024];
            FileInputStream fis = null;
            BufferedInputStream bis = null;
            try {
                fis = new FileInputStream(file);
                bis = new BufferedInputStream(fis);
                OutputStream os = response.getOutputStream();
                int i = bis.read(buffer);
                while (i != -1) {
                    os.write(buffer, 0, i);
                    i = bis.read(buffer);
                }
                System.out.println("success");
            } catch (Exception e) {
                e.printStackTrace();
            } finally {
                if (bis != null) {
                    try {
                        bis.close();
                    } catch (IOException e) {
                        e.printStackTrace();
                    }
                }
                if (fis != null) {
                    try {
                        fis.close();
                    } catch (IOException e) {
                        e.printStackTrace();
                    }
                }
            }
        }
    }
    return null;
}
发布了35 篇原创文章 · 获赞 0 · 访问量 1万+

猜你喜欢

转载自blog.csdn.net/tealala/article/details/100554331