SpringBoot中的上传与下载(十三)

文件上传与下载:

1,使用MultipartFile完成上传,Springboot是使用Servlet3中的Part对象完成上传,不是使用的fileupload;

2,上传相关配置:

spring.http.multipart.enabled=true:是否允许处理上传;

spring.http.multipart.maxFileSize=1MB:允许最大的单文件上传大小,单位可以是kb,mb;

spring.http.multipart.maxRequestSize=10MB:允许的最大请求大小;

 

3,也可以通过创建一个MultipartConfigElement类型的bean对上传进行配置:

@Bean

public MultipartConfigElement multipartConfigElement() {

  MultipartConfigFactory mcf = new MultipartConfigFactory();

  mcf.setMaxFileSize("1MB");

  mcf.setMaxRequestSize("10MB");

  return mcf.createMultipartConfig();

}

 

4,关于上传文件的处理:

因为应用是打成jar包,所以一般会把上传的文件放到其他位置,并通过设置

spring.resources.static-locations

来完成资源位置映射。

spring.resources.static-locations=classpath:/META-INF/resources/,classpath:/resources/,classpath:/static/,classpath:/public/,file:/Users/stef/devs/workspace/springboot-demo/upload/

 

例子,这里用@value注解来引入配置文件变量

application.properties中添加file.path=d:/upload/

Controller类

@Controller
public class FileController {

    //由于项目会打成jar包,所以我们需要自定义盘符目录来上传
    @Value("${file.path}")
    private String filePath;

    @RequestMapping("/upload")
    @ResponseBody
    public String upload(MultipartFile file) throws Exception {
        //获取后缀名
        String endName = file.getOriginalFilename().substring(file.getOriginalFilename().lastIndexOf("."));
        String fileName = UUID.randomUUID().toString() + endName;
        System.out.println(file);
        FileCopyUtils.copy(file.getInputStream(), new FileOutputStream(new File(filePath+fileName)));
        return fileName;
    }

    @RequestMapping("/download")
    public void download(HttpServletRequest request, HttpServletResponse response) throws Exception {
        File file =new File(filePath+"a.jpg");
        InputStream in =new FileInputStream(file);
        response.setContentType("multipart/form-data");
        response.setHeader("Content-Disposition", "attachment;fileName="+"a.png");
        ServletOutputStream out =response.getOutputStream();
        FileCopyUtils.copy(in,out);

        in.close();
        out.close();
    }

}

 前端Form表格要设成 post,且mime类型要设成  multipart/form-data

文件上传:
<form action="/upload" method="post" enctype="multipart/form-data">
    <input type="file" name="file">
    <input type="submit" value="上传">
</form>

 

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值