Skip to content

Instantly share code, notes, and snippets.

@JetXing
Last active July 31, 2017 08:33
Show Gist options
  • Save JetXing/65a39df32c8ddc930c1a0ece2853b1dd to your computer and use it in GitHub Desktop.
Save JetXing/65a39df32c8ddc930c1a0ece2853b1dd to your computer and use it in GitHub Desktop.
MultipartFile save webapp/img,保存图片到本地
private byte[] readInputStream(InputStream inputStream) throws IOException {
ByteArrayOutputStream outputStream = new ByteArrayOutputStream();
byte[] buffer = new byte[1024];
int len = 0;
while ((len = inputStream.read(buffer)) != -1) {
outputStream.write(buffer, 0 ,len);
}
inputStream.close();
return outputStream.toByteArray();
}
public void receiveFile(MultipartFile file, HttpServletRequest request) {
CommonsMultipartFile commonsMultipartFile = (CommonsMultipartFile) file;
DiskFileItem fileItem = (DiskFileItem) commonsMultipartFile.getFileItem();
String realPath = request.getServletContext().getRealPath("/");
String contentType = fileItem.getContentType();
File imageFile = new File(realPath + "img/" + UUID.randomUUID() + "." +
contentType.substring(contentType.indexOf
("/") + 1));
FileOutputStream outputStream = new FileOutputStream(imageFile);
outputStream.write(readInputStream(fileItem.getInputStream()));
outputStream.close();
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment