Max*_*Max 4 spring spring-boot
我开发了一个文件服务器,必须使用 Spring Boot 处理大文件上传(>1GB)。当我不想使用主存时,如何实现上传?
这是我的代码:
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");
}
Run Code Online (Sandbox Code Playgroud)
文件完全上传后开始输出日志,因此我猜测文件已经上传。是否可以将上传内容直接写入文件系统?
提前致谢!最大限度
分段上传将写入磁盘上的临时位置或保存在内存中。正如 javadoc 中所解释的MultipartFile,您有责任在请求处理结束时将文件清除之前将其移动到永久位置。
文件内容要么存储在内存中,要么临时存储在磁盘上。在任一情况下,用户负责根据需要将文件内容复制到会话级或持久存储。请求处理结束时,临时存储将被清除。
您可以通过调用移动内容(从内存或磁盘上的临时位置)MultiPartFile.transferTo(File)。
文件是否保存在内存中或写入临时位置取决于底层实现。例如,Commons File Upload 将在内存中存储小于 10240B 的文件,更大的文件将写入磁盘。
| 归档时间: |
|
| 查看次数: |
6139 次 |
| 最近记录: |