リンクに従ってください。
- アップロード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応答 –
すべての画像を保持し、確認されていない画像を削除してみませんか? 2つの異なる手法を使用するよりも簡単にできます。 – Marged