spring文件下载(一)
我们在前面讲了文件的上传,现在讲讲文件的下载。
文件下载主要就是设置我们Response
的Headers
中"Content-Disposition=attachment;filename=...
。告诉我们浏览器要将数据保存到磁盘上,不在浏览器上直接解析。
前端
这里留一个坑,就是使用ajax
请求前端下载文件是没有反应的,但是使用a
标签就是没有问题
填坑
ajax
回调已经把response
的数据傻瓜式的以字符串的方式解析,ajax
请求只是个“字符型”的请求,即请求的内容是以文本类型存放的。文件的下载是以二进制形式进行的,虽然可以读取到返回的response
,但只是读取而已,console.log
可以打印出读取的字符串,但是无法执行下载的。还可以使用post
请求完成下载。
可以参考
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55
| <%@ page contentType="text/html;charset=UTF-8" language="java" %> <html> <head> <script src="./js/jquery.min.js"></script> <script> let filetype = ""; let url = ""; let showPic = ()=> { let file = $("#file_input")[0].files[0]; let formdata = new FormData(); formdata.set("file", file) formdata.set("abv", "斯大林快回家") $.ajax({ type: "post", processData: false, contentType: false, url: "http://localhost:8080/file_upload_ssm_war_exploded/upload_file", data: formdata, success(resp) { $(".imgFile").attr("src",resp.url); filetype = resp.filetype; url = resp.url; console.log(resp.message); url = "http://localhost:8080/file_upload_ssm_war_exploded/download"+"?filetype="+filetype+"&photo="+resp.url; $("#file_down").attr("href",url); } });
};
</script> <style type="text/css"> .imgFile{ width: 200px; height: 200px; } </style> </head> <body> <h2>Hello World!</h2>
<form action="login"> 用户名:<input name="username"><br> 密码:<input name="password"><br> 头像:<br> <img class="imgFile" src="js:javascript(0)" ><br> <input id="file_input" type="file" name="file" onchange="showPic()"> <a id="file_down" href="javascript:void(0)" >下载</a>
<%-- <input type="submit" /><br>--%>
</form> </body> </html>
|
后端
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69
| package com.zgy.file.controller;
import com.sun.jersey.api.client.Client; import com.sun.jersey.api.client.WebResource; import com.zgy.file.service.FileService; import org.apache.commons.io.IOUtils; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.stereotype.Controller; import org.springframework.web.bind.annotation.RequestBody; import org.springframework.web.bind.annotation.RequestMapping; import org.springframework.web.bind.annotation.ResponseBody; import org.springframework.web.multipart.MultipartFile; import org.springframework.web.servlet.ModelAndView;
import javax.servlet.ServletOutputStream; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse; import java.io.*; import java.net.MalformedURLException; import java.net.URL; import java.util.HashMap; import java.util.Map; import java.util.Optional; import java.util.UUID;
@Controller public class UploadController { public String ServerUrl = "http://127.0.0.1:8090/upload/"; @Autowired FileService service;
@RequestMapping("/test") public ModelAndView test(){ ModelAndView md = new ModelAndView(); md.addObject("hh",service.testSSM()); md.setViewName("forward:/showssm.jsp"); return md; }
@ResponseBody @RequestMapping("/upload_file") public Map<String,String> test(MultipartFile file,String abv,HttpServletRequest req) throws IOException { HashMap<String,String> map = new HashMap<>(); String originalName = file.getOriginalFilename(); String extendName = originalName.substring(originalName.lastIndexOf(".")); String newName = UUID.randomUUID().toString().concat(extendName);
Client client = Client.create(); WebResource resource = client.resource(ServerUrl + newName); System.out.println(resource.put(String.class, file.getBytes())); map.put("message","success"); map.put("url",ServerUrl + newName); map.put("filetype",file.getContentType()); return map; }
@RequestMapping("/download") public void download(String filetype,String photo,HttpServletResponse response) throws IOException { response.setContentType(filetype); String name = photo.substring(photo.lastIndexOf("/")+1); response.setHeader("Content-Disposition", "attachment;filename="+name); InputStream inputStream = new URL(photo).openStream(); ServletOutputStream outputStream = response.getOutputStream(); IOUtils.copy(inputStream,outputStream); } }
|