【Spring boot】文件上传和下载Controller代码

下载

import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
 
import javax.servlet.ServletOutputStream;
import javax.servlet.http.HttpServletResponse;
import java.io.*;
import java.net.URLEncoder;
 
@Controller
@RequestMapping("/down")
public class DownLoadController {
    @RequestMapping("/load")
    public void download(HttpServletResponse response) throws UnsupportedEncodingException {
        String s = URLEncoder.encode("中文.zip", "utf-8");
//       设置content-type:二进制
        response.setHeader("Content-Type", "application/octet-stream");
//        response.setContentType("application/octet-stream");
        response.setHeader("Content-Disposition","attachment;filename="+s);
        try  {
            FileInputStream inputStream = new FileInputStream("d:/his02-0.3.war");
            BufferedInputStream bufferinput = new BufferedInputStream(inputStream);
            ServletOutputStream outputStream = response.getOutputStream();
            BufferedOutputStream bufferedOutput = new BufferedOutputStream(outputStream);
            byte[] bytes = new byte[1024];
            int len=bufferinput.read(bytes);
            while (len!=-1){
                bufferedOutput.write(bytes,0,len);
                bufferedOutput.flush();
                len=bufferinput.read(bytes);
            }
            bufferinput.close();
            bufferedOutput.close();
        } catch (IOException e) {
            e.printStackTrace();
        }
    }
}
上一篇:PostgreSQL 10.0 preview 功能增强 - 回滚范围可精细控制(事务、语句级)


下一篇:如何用adb获得手机里面某个apk的应用信息、版本信息