Spring Mvc下实现以文件流方式下载文件的方法示例
项目中需要对一个点击事件进行下载操作,同时通过点击事件,已经可以从jsp页面获取到需要访问的URL和下载的文件名(数据库获取,jsp页面显示)。点击事件JS如下:
functiondownloadFile(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){//请求成功后处理函数。 varcode=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 publicResultcheckDownload(Stringurl,HttpServletResponseresponse){ Resultresult=Result.createSuccessResult(); HttpURLConnectionconn=null; try{ URLpath=newURL(url); conn=(HttpURLConnection)path.openConnection(); conn.setRequestMethod("GET"); conn.setConnectTimeout(5*1000); conn.getInputStream();//通过输入流获取数据 }catch(IOExceptionex){ result.setCode(0); ex.printStackTrace(); }finally{ if(conn!=null){ conn.disconnect(); } } returnresult; }
如果checkDownload方法中能够正确获得资源,方法返回参数code=1,ajax成功执行:window.location.href=RootPath()+"/todownload?url="+filePath+"&name="+fileName; 调用(todownload)方法,传入url和name,执行文件下载。
@RequestMapping("/todownload") @ResponseBody publicvoiddownload(Stringurl,Stringname,HttpServletResponseresponse){ HttpURLConnectionconn=null; try{ Filefile=newFile(url); //取得文件的后缀名。 Stringext=file.getName().substring(file.getName().lastIndexOf(".")+1).toLowerCase(); StringBufferbuffername=newStringBuffer(name); Stringfilename=buffername.append(".").append(ext).toString(); URLpath=newURL(url); conn=(HttpURLConnection)path.openConnection(); conn.setRequestMethod("GET"); conn.setConnectTimeout(5*1000); InputStreamfis=conn.getInputStream();//通过输入流获取数据 byte[]buffer=readInputStream(fis); if(null!=buffer&&buffer.length>0){ //清空response response.reset(); //设置response的Header response.addHeader("Content-Disposition","attachment;filename="+newString((filename).getBytes("GBK"),"ISO8859_1")); response.addHeader("Content-Length",""+buffer.length); OutputStreamtoClient=response.getOutputStream(); response.setContentType("application/octet-stream"); toClient.write(buffer); toClient.flush(); toClient.close(); } }catch(IOExceptionex){ ex.printStackTrace(); }finally{ if(conn!=null){ conn.disconnect(); } } } /** *从输入流中获取数据 *@paraminStream输入流 *@return *@throwsException */ privatebyte[]readInputStream(InputStreamfis)throwsIOException{ ByteArrayOutputStreamoutStream=newByteArrayOutputStream(); byte[]buffer=newbyte[1024]; intlen=0; while((len=fis.read(buffer))!=-1){ outStream.write(buffer,0,len); } fis.close(); returnoutStream.toByteArray(); }
PS:SpringMVC文件流形式下载(返回)视频文件
importio.swagger.annotations.Api; importio.swagger.annotations.ApiOperation; importorg.springframework.stereotype.Controller; importorg.springframework.web.bind.annotation.RequestMapping; importorg.springframework.web.bind.annotation.RequestMethod; importorg.springframework.web.bind.annotation.RestController; importjavax.servlet.http.HttpServletResponse; importjava.io.File; importjava.io.FileInputStream; importjava.io.IOException; importjava.io.OutputStream; importjava.net.URLEncoder; /** *文件流形式下载视频 *@authorFrontNg *@date2019-05-2309:25 **/ @Controller @RequestMapping(value="/download") @Api(value="下载",tags="下载") publicclassDownloadController{ @ApiOperation(value="下载视频") @RequestMapping(method=RequestMethod.GET) publicvoiddownload(HttpServletResponseresponse)throwsIOException{ Filefile=newFile("/Users/front/Downloads/123.mp4"); FileInputStreaminputStream=newFileInputStream(file); byte[]data=newbyte[(int)file.length()]; intlength=inputStream.read(data); inputStream.close(); StringfileName=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); OutputStreamstream=response.getOutputStream(); stream.write(data); stream.flush(); stream.close(); } }
以上就是本文的全部内容,希望对大家的学习有所帮助,也希望大家多多支持毛票票。