重庆分公司,新征程启航

为企业提供网站建设、域名注册、服务器等服务

怎么在SpringMvc中以文件流方式下载文件

本篇文章给大家分享的是有关怎么在Spring Mvc中以文件流方式下载文件,小编觉得挺实用的,因此分享给大家学习,希望大家阅读完这篇文章后可以有所收获,话不多说,跟着小编一起来看看吧。

十载的饶平网站建设经验,针对设计、前端、开发、售后、文案、推广等六对一服务,响应快,48小时及时工作处理。网络营销推广的优势是能够根据用户设备显示端的尺寸不同,自动调整饶平建站的显示方式,使网站能够适用不同显示终端,在浏览器中调整网站的宽度,无论在任何一种浏览器上浏览网站,都能展现优雅布局与设计,从而大程度地提升浏览体验。成都创新互联从事“饶平网站设计”,“饶平网站推广”以来,每个客户项目都认真落实执行。

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();
  }
}

以上就是怎么在Spring Mvc中以文件流方式下载文件,小编相信有部分知识点可能是我们日常工作会见到或用到的。希望你能通过这篇文章学到更多知识。更多详情敬请关注创新互联行业资讯频道。


标题名称:怎么在SpringMvc中以文件流方式下载文件
文章分享:http://cqcxhl.cn/article/geggjs.html

其他资讯

在线咨询
服务热线
服务热线:028-86922220
TOP