springboot项目关于文件的上传与下载
springboot页面需要实现文件的上传与下载
贴出部分代码
html代码
文件的下载
<form target="name" id="download_dubbo_form" name="download_dubbo_form" method="post" action="/jfpointscore-test/download"> <button id="download_dubbo_config" type="button" class="btn btn-default download_dubbo_config" onclick="download_dubbo_config2();">下载</button> </form>
文件的上传
<form id="upload_dubbo_form" name="upload_dubbo_form" method="post" enctype="multipart/form-data"> <div class="upload_dubbo_container_div"> <font class="upload_dubbo_container_font">请上传dubbo配置:</font><input type="file" id="file" name="file" multiple="multiple" class="btn btn-default upload_dubbo_container_button"/> </div> <div class="upload_dubbo_container_div"> <font class="upload_dubbo_container_font">请上传facade包:</font><input type="file" id="file" name="file" multiple="multiple" class="btn btn-default upload_dubbo_container_button"/> </div> </form>
js部分
下载按钮
//下载按钮 function download_dubbo_config2(){ $.ajax({ type: "post", url: url, cache: false, async : false, timeout: 15000, // 设置超时时间 success: function (data ,textStatus, jqXHR) { if (textStatus == "success") { $("#download_dubbo_form").submit(); } }, error:function (XMLHttpRequest, textStatus, errorThrown) { console.log("请求失败!"); }, complete: function (XMLHttpRequest,status) { if(status == 'timeout') { console.log("网络超时,请刷新"); } } }); }
上传按钮
//上传按钮 function upload_dubbo_config(){ var formData = new FormData($("#upload_dubbo_form")[0]); //重点:要用这种方法接收表单的参数 $.ajax({ type: "post", url: url, cache: false, data: formData, async : true, timeout: 15000, // 设置超时时间 // 告诉jQuery不要去处理发送的数据 processData : false, // 告诉jQuery不要去设置Content-Type请求头 contentType : false, success: function (data ,textStatus, jqXHR) { if (parseInt(data) == 1) { complete = 1; } }, error:function (XMLHttpRequest, textStatus, errorThrown) { console.log("请求失败!"); }, complete: function (XMLHttpRequest,status) { if(status == 'timeout') { console.log("网络超时,请刷新"); } } }); }
后台代码部分需要自行修改,大体代码如下:
package com.jfpointscore.controller; import java.io.BufferedOutputStream; import java.io.File; import java.io.FileInputStream; import java.io.FileOutputStream; import java.util.List; import javax.servlet.ServletOutputStream; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse; import org.springframework.http.ResponseEntity; import org.springframework.web.bind.annotation.RequestMapping; import org.springframework.web.bind.annotation.RequestMethod; import org.springframework.web.bind.annotation.ResponseBody; import org.springframework.web.bind.annotation.RestController; import org.springframework.web.multipart.MultipartFile; import org.springframework.web.multipart.MultipartHttpServletRequest; import com.jfpointscore.entity.common.JsonResponse; @RestController public class FileController { @RequestMapping(value = "/upload", method = RequestMethod.POST) @ResponseBody public String handleFileUpload(HttpServletRequest request){ List<MultipartFile> files = ((MultipartHttpServletRequest)request).getFiles("file"); MultipartFile file = null; BufferedOutputStream stream = null; for (int i =0; i< files.size(); ++i) { file = files.get(i); if (!file.isEmpty()) { try { BufferedOutputStream bufferedOutputStream = new BufferedOutputStream(new FileOutputStream(new File("D:\\logs\\" + file.getOriginalFilename()))); bufferedOutputStream.write(file.getBytes()); bufferedOutputStream.flush(); bufferedOutputStream.close(); } catch (Exception e) { return "You failed to upload " + i + " => " + e.getMessage(); } } else { return "You failed to upload " + i + " because the file was empty."; } } return "1"; } // //文件下载相关代码 // //@RequestMapping(value = "/download",method = RequestMethod.POST) // public String download(@RequestBody Map<String, String> map) throws Exception { // String url = map.get("url"); // BufferedInputStream bis = null; // BufferedOutputStream bos = null; // //获取下载文件露肩 // String downLoadPath = "C:\\Users\\Island\\Desktop\\1533471907(1).png"; // /*response.setHeader("content-type", "application/octet-stream"); // //获取文件的长度 // long fileLength = new File(downLoadPath).length(); // //设置文件输出类型 // response.setContentType("application/octet-stream"); // //设置输出长度 // response.setHeader("Content-Length", String.valueOf(fileLength));*/ // /********************************************************************/ // //获取输入流 // bis = new BufferedInputStream(new FileInputStream(downLoadPath)); // //输出流 // bos = new BufferedOutputStream(new FileOutputStream(new File(url+"\\test.png"))); // byte[] buff = new byte[2048]; // int bytesRead; // while (-1 != (bytesRead = bis.read(buff, 0, buff.length))) { // bos.write(buff, 0, bytesRead); // } // //关闭流 // bis.close(); // bos.close(); // return "1"; //} @RequestMapping(value = "/download",method = RequestMethod.POST) public ResponseEntity<JsonResponse> download(HttpServletRequest req,HttpServletResponse response){ JsonResponse jr = new JsonResponse(); String path = "C:\\Users\\Island\\Desktop\\winscp-download.bat"; // String path = null; try { File file = new File(path); long size = file.length(); String fileName = new String("winscp-download.bat".getBytes("UTF-8"), "iso-8859-1");//为了解决中文名称乱码问题 response.reset(); response.setHeader("Accept-Ranges", "bytes"); //设置文件下载是以附件的形式下载 response.setHeader("Content-disposition", String.format("attachment; filename=\"%s\"", fileName)); response.addHeader("Content-Length", String.valueOf(size)); ServletOutputStream sos = response.getOutputStream(); FileInputStream in = new FileInputStream(file); BufferedOutputStream outputStream = new BufferedOutputStream(sos); byte[] b = new byte[1024]; int i = 0; while ((i = in.read(b)) > 0) { outputStream.write(b, 0, i); } outputStream.flush(); sos.close(); outputStream.close(); in.close(); jr.setStatus("00"); } catch (Exception e) { System.out.println(e); jr = null; } return ResponseEntity.ok(jr); } }