SpringBoot 文件上传下载

SpringBoot 文件上传下载

本章主要介绍了在SpringBoot下的资源文件上传和下载,如有问题,欢迎指出。主要分为两个部分:

  • 文件上传的相关设置
  • 文件下载的相关设置

1. 文件上传

1. application.properties

# 单数据大小
spring.servlet.multipart.max-file-size = 5MB
# 总数据大小
spring.servlet.multipart.max-request-size= 10MB

2. 配置启动类

@Configuration
public class MultipartConfig {

    /**
     * 文件上传设置
     * @return
     */
    @Bean
    public MultipartConfigElement multipartConfigElement() {
        MultipartConfigFactory factory = new MultipartConfigFactory();
        //  单个数据大小
        factory.setMaxFileSize("10240KB"); // KB,MB
        // 总上传数据大小
        factory.setMaxRequestSize("102400KB");
        return factory.createMultipartConfig();
    }

}

3. Controller类

@Autowired
Service service;

@RequestMapping(value = "/uploadMappingTemplate", method = RequestMethod.POST)
public ActionResult uploadExecl(@RequestParam("file")MultipartFile file) {
    String msg = "解析失败";
    try {
		service.resolveExcel(file);
        return actionResult(true, dtos, "");
    } catch (Exception e) {
        e.printStackTrace();
        return actionResult(false, "", e.getMessage() != null ? e.getMessage() : msg);
    }
}

2. 文件下载

一个文件的下载在服务端一共有这么几个步骤:

  1. 搜索到需要下载的文件
  2. 确定是否需要对文件内容进行修改
  3. 提供下载

1. 找到文件

请看我写的另一篇文章:https://www.cnblogs.com/yisany/p/10228719.html

2. 是否需要修改文件

找到文件后,就需要对这个文件内容进行修改,这个是由你的实际情况来决定的,在这儿我需要对文件中的几行内容进行修改:

private String readBash(String filePath, String[] clientIp) {
    BufferedReader br = null;
    String line = null;
    StringBuffer buf = new StringBuffer();

    try {
        // 根据文件路径创建缓冲输入流
        br = new BufferedReader(new FileReader(filePath));
        // 循环读取文件的每一行, 对需要修改的行进行修改, 放入缓冲对象中
        while ((line = br.readLine()) != null) {
            // 此处根据实际需要修改某些行的内容
            if (line.startsWith("ipArray=")) {
                buf.append(line).append("(");
                for (String clientIp : clientIps){
                    buf.append(clientIp).append(" ");
                }
                buf.append(")");
            }
    } catch (Exception e) {
        e.printStackTrace();
    } finally {
        // 关闭流
        if (br != null) {
            try {
                br.close();
            } catch (IOException e) {
                br = null;
            }
        }
    }
    return buf.toString();
}

3. 提供下载

对文件的内容处理完毕之后,就需要提供文件的下载了,这儿有两种方法:

  1. 通过封装ResponseEntity,将文件流写入body中

    @RequestMapping(value = "/media", method = RequestMethod.GET)
    public ResponseEntity<InputStreamResource> downloadFile( Long id) throws IOException {
        String filePath = "E:/" + id + ".rmvb";
        FileSystemResource file = new FileSystemResource(filePath);
        HttpHeaders headers = new HttpHeaders();
        headers.add("Cache-Control", "no-cache, no-store, must-revalidate");
        headers.add("Content-Disposition", String.format("attachment; filename="%s"", file.getFilename()));
        headers.add("Pragma", "no-cache");
        headers.add("Expires", "0");
     
        return ResponseEntity
                .ok()
                .headers(headers)
                .contentLength(file.contentLength())
                .contentType(MediaType.parseMediaType("application/octet-stream"))
                .body(new InputStreamResource(file.getInputStream()));
    }
    
  2. 采用File文件资源,写入到response的输出流中

    @RequestMapping(value="/media/", method=RequestMethod.GET)
    public void getDownload(Long id, HttpServletRequest request, HttpServletResponse response) {
        String content = syslogService.downloadSyslog(unique, serverIp, protocol);
        // 配置文件
        response.setHeader("content-type", "application/octet-stream");
        response.setContentType("application/octet-stream");
        // 配置正常显示中文
        response.setHeader("Content-Disposition", "attachment;filename="
                        + URLEncoder.encode("syslog.sh", "UTF-8"));
        //实现文件下载
        byte[] buffer = new byte[1024];
        InputStream is = new ByteArrayInputStream(content.getBytes());
        BufferedInputStream bis = new BufferedInputStream(is);
        OutputStream os = response.getOutputStream();
        int i = bis.read(buffer);
        while (i != -1){
            os.write(buffer, 0, i);
            i = bis.read(buffer);
        }
        return null;
    }
    

无论是哪一种方法,最重要的是消息头的内容设置。文件的格式需要根据具体文件的类型来设置,一般默认为application/octet-stream

原文地址:https://www.cnblogs.com/yisany/p/10310489.html