Spring Boot商店上传文件
我需要在用户上传图片以显示预览,确认之前,确认后我需要取回并保留图片几分钟。Spring Boot商店上传文件
我想知道做这件事的最佳实践。
我看到了有关Cache和咖啡因,但我不知道这是不是最好的初步实践,以及如何在高速缓存存储与随机哈希后拿回来
[编辑]
也许我高估了这个问题
@Robert建议我会使用临时文件,但我仍然需要一些方法来保证文件将被删除。所以我创建了一个新问题,我会继续帮助其他人用这些术语进行搜索。
按照链接
How guarantee the file will be deleted after automatically some time?
我做这在我的应用程序之一。
- 在上传POST中,我将图像保存到临时文件,然后将临时文件名存储在会话属性中。我使用会话属性,因为正在预览的图像在被写入持久性存储之前不应该对其他任何用户可见。
- 在随后的GET中,我将临时文件名称从会话中拉出,并将其流出到响应中,并在完成时将其删除。由于我不再需要它,所以在预览呈现之后我不打算保留文件。
请参见下面的全面实施:
import java.io.IOException;
import java.io.OutputStream;
import java.nio.file.Files;
import java.nio.file.Path;
import java.nio.file.Paths;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import org.springframework.http.HttpStatus;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestPart;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.multipart.MultipartFile;
@RestController
@RequestMapping("/api/imagePreview")
public class ImagePreviewController
{
@PostMapping
public ResponseEntity<?> post(HttpSession session, @RequestPart MultipartFile file) throws IOException
{
if (file.getContentType() != null && file.getContentType().startsWith("image/")) {
Path tempFile = Files.createTempFile("", file.getOriginalFilename());
file.transferTo(tempFile.toFile());
session.setAttribute("previewImage", tempFile.toFile().getPath());
session.setAttribute("previewImageContentType", file.getContentType());
return ResponseEntity.status(HttpStatus.CREATED).build();
} else {
return ResponseEntity.status(HttpStatus.UNSUPPORTED_MEDIA_TYPE).build();
}
}
@GetMapping
public void get(HttpServletRequest request, HttpServletResponse response) throws IOException
{
HttpSession session = request.getSession(false);
if (session == null) {
response.sendError(HttpServletResponse.SC_NOT_FOUND);
return;
}
String path = (String) session.getAttribute("previewImage");
String contentType = (String) session.getAttribute("previewImageContentType");
if (path == null || contentType == null) {
response.sendError(HttpServletResponse.SC_NOT_FOUND);
return;
}
response.setContentType(contentType);
try (OutputStream out = response.getOutputStream()) {
Files.copy(Paths.get(path), out);
} finally {
Files.deleteIfExists(Paths.get(path));
}
}
}
哦对,但是当用户没有调用get方法时,你会做什么?当这个文件将被删除?这是我的问题,我如何确定该文件将被删除? –
感谢您的想法@robert。我创建了另一个关于使用临时文件的问题http://stackoverflow.com/questions/43483750/how-guarantee-the-file-will-be-deleted-after-automatically-some-time –
你得到的HTTP响应的形象呢?或者是什么? –
是的,来自HTTP响应 –
为什么不保留所有图像并删除那些未确认的图像?可能比涉及两种不同的技术更简单。 – Marged