JAVA文件以流的形式存在Mysql(blob)数据库,mysql最大支持4G文件(longblb)
直接将流转换为byte存入数据库
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
| public Response uploadBlob(MultipartFile file) { FileUpload fileUpload = new FileUpload(); fileUpload.setFileName(file.getOriginalFilename()); try { fileUpload.setContent(FileTypeUtils.input2byte(file.getInputStream())); } catch (IOException e) { e.printStackTrace(); } save(fileUpload); return Response.ok("成功", fileUpload.getId()); }
public static byte[] input2byte(InputStream inStream) throws IOException { try (ByteArrayOutputStream swapStream = new ByteArrayOutputStream()) { byte[] buff = new byte[inStream.available()]; while (inStream.read(buff) != -1) { swapStream.write(buff); } return swapStream.toByteArray(); } catch (Exception e) { e.printStackTrace(); } return null; }
|
下载文件输出文件流到前端
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
| public void getFile(String id, HttpServletRequest request, HttpServletResponse response) throws UnsupportedEncodingException { FileUpload fileUpload = getById(id); if (fileUpload.getContent() != null) { String filename = fileUpload.getFileName(); String userAgent = request.getHeader("USER-AGENT"); if (StringUtils.contains(userAgent, "MSIE")) { filename = URLEncoder.encode(filename, "UTF8"); } else if (StringUtils.contains(userAgent, "Mozilla")) { filename = new String(filename.getBytes(), "ISO8859-1"); } else { filename = URLEncoder.encode(filename, "UTF8"); } try { byte[] fileStream = fileUpload.getContent(); response.setHeader("content-type", "application/octet-stream"); response.setContentType("application/octet-stream"); response.setHeader("Content-Disposition", "attachment;filename=" + URLEncoder.encode(filename, "UTF-8")); OutputStream toClient = new BufferedOutputStream(response.getOutputStream()); toClient.write(fileStream); toClient.flush(); toClient.close(); } catch (Exception e) { e.printStackTrace(); } } }
|
流的方式前端要指定 responseType: ‘blob’
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20
| methods: { downLoad() { if (this.fileId) { request({ url: "localhost:8080/file/getFile", method: "get", params: { id: this.fileId }, responseType: 'blob' }).then((resp) => { let blob = new Blob([resp],{ type:'application/vnd.ms-excel' }); let objectUrl = URL.createObjectURL(blob); this.downloadFile(objectUrl,this.form.fileName) }); } } }
|
转成文件
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19
| public File getFile(String id, HttpServletRequest request, HttpServletResponse response) { FileUpload fileUpload = getById(id); if (fileUpload.getContent() != null) { File file = null; try { file = new File(fileUpload.getFileName()); if (!file.exists()) { file.createNewFile(); } OutputStream os = new FileOutputStream(file); os.write(fileUpload.getContent()); os.close(); } catch (Exception e) { e.printStackTrace(); } return file; } }
|