Spring mvc文件上传下载代码实例

2020-03-19 16:02:26于海丽

前端表单提交地址修改

访问提交测试

文件下载
文件下载步骤:

设置 response 响应头 读取文件 -- InputStream 写出文件 -- OutputStream 执行操作 关闭流 (先开后关)

代码实现:

@RequestMapping(value="/download")
public String downloads(HttpServletResponse response ,HttpServletRequest request) throws Exception{
  //要下载的图片地址
  String path = request.getServletContext().getRealPath("/upload");
  String fileName = "基础语法.jpg";

  //1、设置response 响应头
  response.reset(); //设置页面不缓存,清空buffer
  response.setCharacterEncoding("UTF-8"); //字符编码
  response.setContentType("multipart/form-data"); //二进制传输数据
  //设置响应头
  response.setHeader("Content-Disposition",
      "attachment;fileName="+URLEncoder.encode(fileName, "UTF-8"));

  File file = new File(path,fileName);
  //2、 读取文件--输入流
  InputStream input=new FileInputStream(file);
  //3、 写出文件--输出流
  OutputStream out = response.getOutputStream();

  byte[] buff =new byte[1024];
  int index=0;
  //4、执行 写出操作
  while((index= input.read(buff))!= -1){
    out.write(buff, 0, index);
    out.flush();
  }
  out.close();
  input.close();
  return null;
}

前端

<a href="/download" rel="external nofollow" >点击下载</a>

以上就是本文的全部内容,希望对大家的学习有所帮助,也希望大家多多支持易采站长站。