- 文件转换 file 转 MultipartFile
代码:
/** * @Description file ת MultipartFile * @author wjl * @date 2019/8/23 0023 * @param [file] * @return org.springframework.web.multipart.MultipartFile */ public static MultipartFile fileToMultiPartFile(File file){ LocalDateTime localDateTime=LocalDateTime.now(); String fileExt=localDateTime.getYear()+"-"+localDateTime.getMonth().getValue()+"-"+localDateTime.getDayOfMonth()+"-"; MultipartFile multipartFile=new MultipartFile() { @Override public String getName() { return fileExt+file.getName(); } @Override public String getOriginalFilename() { return fileExt+file.getName(); } @Override public String getContentType() { return null; } @Override public boolean isEmpty() { return file==null ? true :false; } @Override public long getSize() { return 0; } @Override public byte[] getBytes() { return File2byte(file); } @Override public InputStream getInputStream() throws IOException { return new FileInputStream(file); } @Override public void transferTo(File file) throws IOException, IllegalStateException { } }; return multipartFile; }
- 文件转字数组
/** * 将文件转字节数组 * @param filePath * @return */ public static byte[] File2byte(File tradeFile){ byte[] buffer = null; try { FileInputStream fis = new FileInputStream(tradeFile); ByteArrayOutputStream bos = new ByteArrayOutputStream(); byte[] b = new byte[1024]; int n; while ((n = fis.read(b)) != -1) { bos.write(b, 0, n); } fis.close(); bos.close(); buffer = bos.toByteArray(); }catch (FileNotFoundException e){ e.printStackTrace(); }catch (IOException e){ e.printStackTrace(); } return buffer; }
来源:博客园
作者:suc-浮生
链接:https://www.cnblogs.com/wangsr-suc/p/11412056.html