Last active
July 31, 2017 08:33
-
-
Save JetXing/65a39df32c8ddc930c1a0ece2853b1dd to your computer and use it in GitHub Desktop.
MultipartFile save webapp/img,保存图片到本地
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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