springmvc实现上传和下载

非常简单的小例子,注释的很清楚。话不多少,看代码

FileController.java
package com.imooc;

import org.apache.commons.io.IOUtils;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.multipart.MultipartFile;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.File;
import java.io.FileInputStream;
import java.io.InputStream;
import java.io.OutputStream;
import java.util.Date;

/**
 * Created by 敲代码的卡卡罗特
 * on 2018/4/15 16:52.
 */
@RequestMapping("/file")
@Controller
public class FileController {
    private String folder="E://update";
    @PostMapping
    public void upload(MultipartFile file) throws Exception {

        System.out.println(file.getName());  //file  就是你前台传过来的参数名字
        System.out.println(file.getOriginalFilename());  //idea快捷键.txt  就是你文件的实际名字
        System.out.println(file.getSize()); //文件的大小

        //这里只是一个小demo,按理说应该截取传过来的后缀的,这里写死了。
        File localFile = new File(folder, new Date().getTime() + ".txt");
        //复制到这个文件中
        file.transferTo(localFile);
    }

    @GetMapping("/{id}")
    public void download(@PathVariable String id, HttpServletRequest request, HttpServletResponse response) throws Exception {
        //这个是jdk1.7的新用法,把流写在try的括号里面,就不用最后关闭流了。帮你做了
        try (InputStream inputStream = new FileInputStream(new File(folder, id + ".txt"));
             OutputStream outputStream = response.getOutputStream();) {
            //设置信息头
            response.setContentType("application/x-download");
            response.addHeader("Content-Disposition", "attachment;filename=test.txt");//filename 就是你下载到本地的名字

            //意思是把输入流复制到输出流中
            IOUtils.copy(inputStream, outputStream);
            outputStream.flush();
        }

    }
}
View Code

解决中文文件名————问题

 String name = URLEncoder.encode(file.getFilename(), "utf-8")
依赖看引入的包。就不写了。
原文地址:https://www.cnblogs.com/coder-lzh/p/8848320.html