Skip to content

Instantly share code, notes, and snippets.

@syakuis
Last active May 2, 2022 13:13
Show Gist options
  • Save syakuis/448b91cab8bd246098543c21998e594f to your computer and use it in GitHub Desktop.
Save syakuis/448b91cab8bd246098543c21998e594f to your computer and use it in GitHub Desktop.
toMultipartFile
import org.apache.commons.fileupload.FileItem;
import org.apache.commons.fileupload.disk.DiskFileItem;
import org.apache.commons.io.IOUtils;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.http.MediaType;
import org.springframework.stereotype.Service;
import org.springframework.web.multipart.MultipartFile;
import org.springframework.web.multipart.commons.CommonsMultipartFile;
import java.io.IOException;
import java.io.InputStream;
import java.net.URL;
import java.nio.file.Files;
import java.nio.file.Path;
import java.nio.file.Paths;
@Service
public class VehicleImageSaveService {
private String uri = "http 이미지 url";
public MultipartFile getMultipartFile(String relativePath, String filename) throws IOException {
String tempDir = System.getProperty("java.io.tmpdir");
Path image = Paths.get(tempDir, filename);
if (!Files.exists(image)) {
try (InputStream in = new URL(uri + "/" + relativePath).openStream()) {
// 자바 임시 저장소 저장
Files.copy(in, image);
}
}
// Multiparfile 생성
try (InputStream in = Files.newInputStream(image)) {
FileItem fileItem = new DiskFileItem(image.getFileName().toString(), MediaType.parseMediaType(Files.probeContentType(image)).getType(), false, image.getFileName().toString(), (int) Files.size(image), image.getParent().toFile());
IOUtils.copy(in, fileItem.getOutputStream());
return new CommonsMultipartFile(fileItem);
}
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment