欢迎您访问程序员文章站本站旨在为大家提供分享程序员计算机编程知识!
您现在的位置是: 首页  >  IT编程

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

程序员文章站 2023-11-24 13:38:40
项目中需要对一个点击事件进行下载操作,同时通过点击事件,已经可以从jsp页面获取到需要访问的url和下载的文件名(数据库获取,jsp页面显示)。点击事件js如下:...

项目中需要对一个点击事件进行下载操作,同时通过点击事件,已经可以从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();
  }
}

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