import java.io.File; import java.io.IOException; import java.net.URLEncoder; import java.util.UUID; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.core.io.FileSystemResource; import org.springframework.core.io.InputStreamResource; import org.springframework.http.HttpHeaders; import org.springframework.http.MediaType; import org.springframework.http.ResponseEntity; import org.springframework.web.bind.annotation.PostMapping; import org.springframework.web.bind.annotation.RequestMapping; import org.springframework.web.bind.annotation.RequestMethod; import org.springframework.web.bind.annotation.RestController; import org.springframework.web.multipart.MultipartFile; import dao.upAnddownDao; import po.Sdownload; @RestController @RequestMapping("/test") public class textController { @Autowired private upAnddownDao uad; // 上传 @PostMapping("/upload") // 必须要有MultipartFile类型参数。而且参数名必须与表单file控件名一致 public String upload(MultipartFile file) { // 上传图片存储目录 String path = "d:/upload"; // 获取文件名并使用UUID生成新文件名 System.out.println(file); String fileName = file.getOriginalFilename(); System.out.println(fileName); System.out.println(fileName.substring(fileName.lastIndexOf("."))); String newFileName = UUID.randomUUID() + fileName.substring(fileName.lastIndexOf(".")); // 在指定上传图片存储目录中创建新文件 File targetFile = new File(path, newFileName); // 如果找不到指定目录和文件,就新创建此目录和文件 if (!targetFile.exists()) { targetFile.mkdirs(); } // 将文件写入硬盘(myFile在内存中) try { file.transferTo(targetFile); } catch (Exception e) { e.printStackTrace(); } Sdownload dl = new Sdownload(); String url = path + "/" + newFileName; System.out.println(url); dl.setUrl(url); dl.setDeltag(0); Integer result = uad.upload(dl); System.out.println(result); return "ok"; } // 下载 @RequestMapping(value = "/down", method = RequestMethod.GET) public ResponseEntity<InputStreamResource> downfile(Integer dlid) throws IOException { System.out.println(dlid); Sdownload sdl = uad.download(dlid); String url = sdl.getUrl(); // 明确要读取的文件 File file = new File(url); FileSystemResource fsr = new FileSystemResource(file); // 设置响应输出流的头部信息 HttpHeaders hh = new HttpHeaders(); String fname = URLEncoder.encode(file.getName(), "utf-8"); System.out.println(fname); hh.add("Content-Disposition", "attachment;filename=\"" + fname + "\""); hh.add("Cache-Control", "no-cache, no-store, must-revalidate"); hh.add("Pragma", "no-cache"); hh.add("Expires", "0"); // 完成响应输出 return ResponseEntity.ok().headers(hh).contentLength(fsr.contentLength()) .contentType(MediaType.parseMediaType("application/octet-stream;charset=utf-8")) .body(new InputStreamResource(fsr.getInputStream())); } }
vue下载:
// 下载 downPDF() { let url = "" ; let that = this; this.$axios.get(url, { // 下载文件响应设局类型设计为blob responseType: 'blob' }) .then(resp => { console.log(resp); console.log(resp.data); console.log(typeof resp.data); // 根据响应头部信息获取下载文件名 let info = resp.headers['content-disposition']; console.log(info); let arr = info.split('='); console.log(arr[0]); console.log(arr[1]); let initialname = arr[1]; let filename = decodeURIComponent(initialname); console.log(filename); // 获取下载文件的数据 let blob = resp.data; // JavaScript的文件输入流 let fileReader = new FileReader(); fileReader.readAsDataURL(blob); fileReader.onload = function(event) { let mydata = event.target.result; // 创建超级链接标签 let a = document.createElement('a'); a.href = mydata; // 在下载时后缀会多个下划线,filename.replace(new RegExp('"', 'g'), '');来解决 // a.download = filename; a.download = filename.replace(new RegExp('"', 'g'), ''); // 把超级链接追加到页面 document.body.appendChild(a); // 通过click方法模拟点击超级链接完成下载的过程 a.click(); document.body.removeChild(a); } }) .catch(error => { console.log(error); }); },
vue上传:
<div> <input type="file" ref="myfile" v-on:change="selectFile"> <input type="button" value="点击文件上传" v-on:click="upload"> </div> // 选择文件 selectFile:function(){ // 得到文本框对象 let wenbenkuang=this.$refs['myfile']; // 得到上传的文件 this.fileObj=wenbenkuang.files[0]; console.log(this.fileObj); }, upload:function(){ // 表单序列化 let mydata=new FormData(); mydata.append("file",this.fileObj); // 调用axios // let url='web/upload'; let url='test/upload'; this.$axios.post(url,mydata,{ headers:{ 'Content-type':'multipart/form-data' } }) .then(resp=>{ let result=resp.data; alert(result); }) .catch(error=>{ console.log(error); }); },