您好,登錄后才能下訂單哦!
這期內容當中小編將會給大家帶來有關使用springboot怎么樣實現一個文件上傳下載功能,文章內容豐富且以專業的角度為大家分析和敘述,閱讀完這篇文章希望大家可以有所收獲。
1.文件上傳(前端頁面):
<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd"> <html> <head> <meta http-equiv="Content-Type" content="text/html; charset=UTF-8"> <title>Insert title here</title> </head> <body> <form action="/testUpload" method="POST" enctype="multipart/form-data"> <input type="file" name="file"/> <input type="submit" /> </form> <a href="/testDownload" rel="external nofollow" >下載</a> </body> </html>
表單提交加上enctype="multipart/form-data"很重要,文件以二進制流的形式傳輸。
2.文件上傳(后端java代碼)支持多文件
Way1.使用MultipartHttpServletRequest來處理上傳請求,然后將接收到的文件以流的形式寫入到服務器文件中:
@RequestMapping(value="/testUpload",method=RequestMethod.POST) public void testUploadFile(HttpServletRequest req,MultipartHttpServletRequest multiReq) throws IOException{ FileOutputStream fos=new FileOutputStream(new File("F://test//src//file//upload.jpg")); FileInputStream fs=(FileInputStream) multiReq.getFile("file").getInputStream(); byte[] buffer=new byte[1024]; int len=0; while((len=fs.read(buffer))!=-1){ fos.write(buffer, 0, len); } fos.close(); fs.close(); }
Way2.也可以這樣來取得上傳的file流:
// 文件上傳 @RequestMapping("/fileUpload") public Map fileUpload(@RequestParam("file") MultipartFile file, HttpServletRequest req) { Map result = new HashMap(); SimpleDateFormat df = new SimpleDateFormat("yyyyMMdd");// 設置日期格式 String dateDir = df.format(new Date());// new Date()為獲取當前系統時間 String serviceName = UuidUtil.get32UUID() + file.getOriginalFilename().substring(file.getOriginalFilename().lastIndexOf(".")); File tempFile = new File(fileDir + dateDir + File.separator + serviceName); if (!tempFile.getParentFile().exists()) { tempFile.getParentFile().mkdirs(); } if (!file.isEmpty()) { try { BufferedOutputStream out = new BufferedOutputStream(new FileOutputStream(tempFile)); // "d:/"+file.getOriginalFilename() 指定目錄 out.write(file.getBytes()); out.flush(); out.close(); } catch (FileNotFoundException e) { e.printStackTrace(); result.put("msg", "上傳失敗," + e.getMessage()); result.put("state", false); return result; } catch (IOException e) { e.printStackTrace(); result.put("msg", "上傳失敗," + e.getMessage()); result.put("state", false); return result; } result.put("msg", "上傳成功"); String fileId = Get8uuid.generateShortUuid(); String fileName = file.getOriginalFilename(); String fileType = fileName.substring(fileName.lastIndexOf(".") + 1); String fileUrl = webDir + dateDir + '/' + serviceName; uploadMapper.saveFileInfo(fileId, serviceName, fileType, fileUrl); result.put("state", true); return result; } else { result.put("msg", "上傳失敗,因為文件是空的"); result.put("state", false); return result; }
3.application.properties配置文件
#上傳文件大小設置 multipart.maxFileSize=500Mb multipart.maxRequestSize=500Mb
4.文件下載將文件寫到輸出流里:
@RequestMapping(value="/testDownload",method=RequestMethod.GET) public void testDownload(HttpServletResponse res) throws IOException{ File file = new File("C:/test.txt"); resp.setHeader("content-type", "application/octet-stream"); resp.setContentType("application/octet-stream"); resp.setHeader("Content-Disposition", "attachment;filename=" + fileName); byte[] buff = new byte[1024]; BufferedInputStream bis = null; OutputStream os = null; try { os = resp.getOutputStream(); bis = new BufferedInputStream(new FileInputStream(file)); int i = bis.read(buff); while (i != -1) { os.write(buff, 0, buff.length); os.flush(); i = bis.read(buff); } } catch (IOException e) { e.printStackTrace(); } finally { if (bis != null) { try { bis.close(); } catch (IOException e) { e.printStackTrace(); } } } }
5.獲取文件大小
// 文件大小轉換 DecimalFormat df1 = new DecimalFormat("0.00"); String fileSizeString = ""; long fileSize = file.getSize(); if (fileSize < 1024) { fileSizeString = df1.format((double) fileSize) + "B"; } else if (fileSize < 1048576) { fileSizeString = df1.format((double) fileSize / 1024) + "K"; } else if (fileSize < 1073741824) { fileSizeString = df1.format((double) fileSize / 1048576) + "M"; } else { fileSizeString = df1.format((double) fileSize / 1073741824) + "G"; }
如果是File類則fileSize=file.length()。
上述就是小編為大家分享的使用springboot怎么樣實現一個文件上傳下載功能了,如果剛好有類似的疑惑,不妨參照上述分析進行理解。如果想知道更多相關知識,歡迎關注億速云行業資訊頻道。
免責聲明:本站發布的內容(圖片、視頻和文字)以原創、轉載和分享為主,文章觀點不代表本網站立場,如果涉及侵權請聯系站長郵箱:is@yisu.com進行舉報,并提供相關證據,一經查實,將立刻刪除涉嫌侵權內容。