问题
I develope a fileserver that has to handle large file uploads (>1G B) with spring boot. How can I implement the upload when I do not want to use the main memory?
This is my code:
final String id = GenerationHelper.uuid();
final File newFile = new File(id);
LOG.info("New file: " + id + " with size " + content.getSize());
if (!content.isEmpty()) {
FileInputStream in = null;
FileOutputStream out = null;
long totalBytes = 0;
try {
in = (FileInputStream) content.getInputStream();
out = new FileOutputStream(newFile);
byte[] buffer = new byte[1024];
int bytesRead = 0;
while ((bytesRead = in.read(buffer)) != -1) {
out.write(buffer);
totalBytes += bytesRead;
LOG.info(bytesRead);
}
} catch (IOException e) {
LOG.error("Failed to save file", e);
newFile.delete();
} finally {
try {
in.close();
out.close();
} catch (IOException e) {
LOG.error("Error creating new file with id " + id + ". Deleting this file...", e);
}
}
LOG.info(totalBytes + " Bytes read");
}
The log output starts after the file has been uploaded completely so I guess that the file has been already uploaded. Is it possible to write an upload directly to the filesystem?
Thanks in advance! Max
回答1:
The multipart upload will be written to a temporary location on disk or held in memory. As explained in the javadoc for MultipartFile
, it's then your responsibility to move the file to a permanent location before it's cleaned up at the end of the request processing.
The file contents are either stored in memory or temporarily on disk. In either case, the user is responsible for copying file contents to a session-level or persistent store as and if desired. The temporary storages will be cleared at the end of request processing.
You can move the contents (from memory or the temporary location on disk) by calling MultiPartFile.transferTo(File)
.
Whether or not the file is held in memory or written to a temporary location depends on the underlying implementation. For example, Commons File Upload will store files less than 10240B in memory, with anything bigger being written to disk.
来源:https://stackoverflow.com/questions/34296470/how-does-spring-multipart-file-upload-exactly-work