Spring Mvc下实现以文件流方式下载文件的方法示例

作者:爱吃牛奶糖 时间:2023-11-12 10:14:22 

项目中需要对一个点击事件进行下载操作,同时通过点击事件,已经可以从jsp页面获取到需要访问的URL和下载的文件名(数据库获取,jsp页面显示)。点击事件JS如下:


function downloadFile(filePath,fileName){

fileName = fileName.substr(0,fileName.lastIndexOf("."));
$.ajax({
  async : false,
  cache:false,
  type: 'get',
  dataType : "json",
  url: RootPath() + "/checkDownload",//请求的action路径
  data:{url:filePath},
  error: function () {//请求失败处理函数
    alert("下载失败");
  },
  success:function(json) { //请求成功后处理函数。
  var code = json.code;
  if(code) {
   window.location.href = RootPath()+"/todownload?url="+filePath+"&name="+fileName;
  }else {
   layer.alert(fileName+' 文件不存在');
  }
  }
});

}

该ajax调用后台(checkDownload)方法,首先判断从该url能否获得指定下载的文件,如果获取不到,方法返回参数code=0,页面弹出“...文件不存在”。


@RequestMapping("/checkDownload")
@ResponseBody
public Result checkDownload(String url,HttpServletResponse response) {
Result result = Result.createSuccessResult();
HttpURLConnection conn = null;
try {
 URL path = new URL(url);
 conn = (HttpURLConnection) path.openConnection();
 conn.setRequestMethod("GET");
 conn.setConnectTimeout(5 * 1000);
 conn.getInputStream();// 通过输入流获取数据
} catch (IOException ex) {
 result.setCode(0);
 ex.printStackTrace();
}finally {
 if(conn != null) {
 conn.disconnect();
 }
}
return result;
}

如果checkDownload方法中能够正确获得资源,方法返回参数code=1,ajax成功执行:window.location.href = RootPath()+"/todownload?url="+filePath+"&name="+fileName;   调用(todownload)方法,传入url和name,执行文件下载。


@RequestMapping("/todownload")
@ResponseBody
public void download(String url, String name, HttpServletResponse response) {
HttpURLConnection conn = null;
try {
 File file = new File(url);
 // 取得文件的后缀名。
 String ext = file.getName().substring(file.getName().lastIndexOf(".") + 1).toLowerCase();
 StringBuffer buffername = new StringBuffer(name);
 String filename = buffername.append(".").append(ext).toString();

URL path = new URL(url);
 conn = (HttpURLConnection) path.openConnection();
 conn.setRequestMethod("GET");
 conn.setConnectTimeout(5 * 1000);
 InputStream fis = conn.getInputStream();// 通过输入流获取数据

byte[] buffer = readInputStream(fis);
 if (null != buffer && buffer.length > 0) {
 // 清空response
 response.reset();
 // 设置response的Header
 response.addHeader("Content-Disposition","attachment;filename="+ new String((filename).getBytes("GBK"),"ISO8859_1"));
 response.addHeader("Content-Length", "" + buffer.length);
 OutputStream toClient = response.getOutputStream();
 response.setContentType("application/octet-stream");
 toClient.write(buffer);
 toClient.flush();
 toClient.close();
 }

} catch (IOException ex) {
 ex.printStackTrace();
}finally {
 if(conn != null) {
 conn.disconnect();
 }
}
}

/**
  * 从输入流中获取数据
  * @param inStream 输入流
  * @return
  * @throws Exception
  */
private byte[] readInputStream(InputStream fis) throws IOException {
 ByteArrayOutputStream outStream = new ByteArrayOutputStream();
    byte[] buffer = new byte[1024];
    int len = 0;
    while( (len=fis.read(buffer)) != -1 ){
      outStream.write(buffer, 0, len);
    }
    fis.close();
    return outStream.toByteArray();
}

PS:Spring MVC 文件流形式下载(返回)视频文件


import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RestController;

import javax.servlet.http.HttpServletResponse;
import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;
import java.io.OutputStream;
import java.net.URLEncoder;

/**
* 文件流形式下载视频
* @author Front Ng
* @date 2019-05-23 09:25
**/

@Controller
@RequestMapping(value = "/download")
@Api(value = "下载", tags = "下载")
public class DownloadController {

@ApiOperation(value = "下载视频")
 @RequestMapping(method = RequestMethod.GET)
 public void download(HttpServletResponse response) throws IOException {

File file = new File("/Users/front/Downloads/123.mp4");

FileInputStream inputStream = new FileInputStream(file);
   byte[] data = new byte[(int) file.length()];
   int length = inputStream.read(data);
   inputStream.close();

String fileName = URLEncoder.encode("文件流形式视频.mp4", "UTF-8");

response.setContentType("application/octet-stream;charset=UTF-8");
   response.setHeader("Content-Disposition", "attachment; filename=\"" + fileName + "\"");
   response.addHeader("Content-Length", "" + data.length);

OutputStream stream = response.getOutputStream();
   stream.write(data);
   stream.flush();
   stream.close();
 }
}

来源:https://blog.csdn.net/u011232863/article/details/79931509

标签:Spring,Mvc,文件流,下载
0
投稿

猜你喜欢

  • Android程序锁的实现以及逻辑

    2022-09-29 19:50:57
  • C#数据结构之双向链表(DbLinkList)实例详解

    2023-08-23 08:56:44
  • Android性能优化之JVMTI与内存分配

    2021-11-06 13:25:06
  • Android编程之Sdcard相关代码集锦

    2022-08-15 09:55:24
  • Android中SQLite数据库知识点总结

    2021-10-03 10:57:13
  • SpringBoot用@Async注解实现异步任务

    2023-08-07 06:36:09
  • Netty分布式pipeline管道异常传播事件源码解析

    2021-08-15 16:12:02
  • Java实现简单的日历界面

    2021-10-08 03:13:01
  • Java实现多个wav文件合成一个的方法示例

    2021-10-08 08:14:25
  • Android开发flow常见API的使用示例详解

    2021-09-25 05:27:49
  • java验证电话号码的方法

    2023-04-01 21:44:41
  • SpringBoot + SpringSecurity 短信验证码登录功能实现

    2022-10-16 10:26:25
  • Android图片色彩变换实现方法

    2022-03-21 07:23:32
  • 详解SpringCloud Ribbon 负载均衡通过服务器名无法连接的神坑

    2021-06-01 07:28:41
  • Java爬虫实现Jsoup利用dom方法遍历Document对象

    2023-06-15 07:52:36
  • C#图像处理之图像平移的方法

    2021-12-16 08:38:37
  • java设计模式之简单工厂模式简述

    2021-06-14 17:11:20
  • java明文密码三重加密方法

    2022-09-01 05:59:26
  • 详解Spring Data JPA使用@Query注解(Using @Query)

    2023-11-29 14:49:34
  • datatable生成excel和excel插入图片示例详解

    2022-06-18 21:48:38
  • asp之家 软件编程 m.aspxhome.com