SpringMVC中文件的上传与下载

##文件的上传:
@RequestMapping("/upload")
//@RequestParam(“upload”)是表单中name属性,上传的文件封装到了CommonsMultipartFile file里
public String show2(@RequestParam(“upload”) CommonsMultipartFile file,HttpSession session) throws Exception {
System.out.println(file.getContentType()); //文件类型
System.out.println(file.getOriginalFilename()); //文件名
System.out.println(file.getSize()); //文件大小
System.out.println(file.getName()); //表单中文件所在的框的name属性的名称,其实就是@RequestParam(“upload”)

    String filename = file.getOriginalFilename();//获取文件名称
    //确定上传的路径
    String realPath = session.getServletContext().getRealPath("/upload" );
    //创建文件上传的目录(或者说是文件夹)
    File uploadPath = new File(realPath);
    if(!uploadPath.exists()){
        //判断如果这个文件夹不存在,就立即新建一个
        uploadPath.mkdirs();
    }
    //确认最终的路径:文件夹+文件名
    uploadPath = new File(uploadPath + "/" + filename);
    //开始上传
    file.transferTo(uploadPath);

    return "success";
}

##文件的下载:
//注意,rest风格会默认忽略扩展名(a标签问号传值不会出现这个问题),解决办法是后面加上:.+
@RequestMapping("/download/{f_name:.+}")
public ResponseEntity show(@PathVariable String f_name, HttpSession session) throws Exception{
System.out.println(f_name);

    //1.获取文件的真实路径
    String realPath = session.getServletContext().getRealPath("/download/" + f_name);

    //2.把文件读到程序中
    InputStream io = new FileInputStream(realPath);  //输入流管道
    byte[] body = new byte[io.available()]; //装字节的桶,将读的文件字节流存进去
    io.read(body);

    //3.创建响应头,给浏览器
    //创建的这个响应头是springMVC内部提供的
    HttpHeaders httpHeaders = new HttpHeaders();
    //文件名为中文时,需要编码,否则下载的时候没有名称
    f_name = URLEncoder.encode(f_name, "UTF-8");
    //给响应头添加信息,Content-Disposition是固定的,attachment告诉浏览器是附件,
    httpHeaders.add("Content-Disposition","attachment;filename="+f_name);
    ResponseEntity<byte[]> responseEntity = new ResponseEntity<>(body, httpHeaders, HttpStatus.OK);

    return responseEntity;
}
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值