我做这在我的应用程序之一。
- 在上传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));
}
}
}
你得到的HTTP响应的形象呢?或者是什么? –
是的,来自HTTP响应 –
为什么不保留所有图像并删除那些未确认的图像?可能比涉及两种不同的技术更简单。 – Marged