SpringMVC文件上传与下载(使用StandardServletMultipartResolver)

SpringMVC文件上传与下载


一、上传
1.在springMVC配置文件中声明multipart解析器。使用StandardServletMultipartResolver不需要导入额外的jar包

<bean id="multipartResolver" class="org.springframework.web.multipart.support.StandardServletMultipartResolver">
</bean>

2.web.xml配置Multipart,我们必须指定文件上传过程中所写入的临时文件路径,否则StandardServletMultipartResolver无法正常工作

<servlet>
    <servlet-name>dispatcher</servlet-name>
    <servlet-class>org.springframework.web.servlet.DispatcherServlet</servlet-class>
    <init-param>
        <param-name>contextConfigLocation</param-name>
        <param-value>WEB-INF/dispatcher-servlet.xml</param-value>
    </init-param>
    <load-on-startup>1</load-on-startup>
    <multipart-config>
        <location>E://topic/tmp/uploads</location>
    </multipart-config>
</servlet>
<servlet-mapping>
    <servlet-name>dispatcher</servlet-name>
    <url-pattern>/</url-pattern>
</servlet-mapping>

3.文件上传Controller方法

@ResponseBody
@PostMapping("/upload/{topicId}")
public Map upload(@PathVariable int topicId, @RequestPart("file") MultipartFile file) {

    Map map=new HashMap();
    map.put("code","0");
    try{
        String original = file.getOriginalFilename();        //获取文件名
        String suffix = original.substring(original.lastIndexOf('.')); //获取文件后缀
        String filename = "E://topic/uploads/调查报告"+topicId+suffix;   //重名名
        file.transferTo(new File(filename));                //写入文件系统
        Map m = new HashMap();
        m.put("src",filename);
        map.put("data",m);
        map.put("msg","上传成功!");
    }catch (Exception e){
        map.put("data",null);
        map.put("msg","上传失败!");
    }
    return map;
}

二、下载
1.文件下载Controller方法

@GetMapping("/download/{topicId}")
public ResponseEntity<byte[]> download(@PathVariable int topicId) throws IOException {
    String filename=surveyService.getPath(topicId);  //surveyService.getPath获取文件路径
    File file = new File(filename);
    InputStream is = new FileInputStream(file);
    byte[] body = new byte[is.available()];
    is.read(body);
    is.close();
    HttpHeaders headers = new HttpHeaders();
    headers.set("Content-Disposition", "attachment;filename=" + file.getName());
    HttpStatus statusCode = HttpStatus.OK;
    ResponseEntity<byte[]> entity = new ResponseEntity<byte[]>(body, headers, statusCode);
    return entity;
}

2.前端请求下载文件时,不能使用ajax,使用ajax请求下载时浏览器不会弹出下载提示框,可使用window.location.href进行请求

window.location.href = "/topic/download/" + id;
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值