package com.example.server.utils;
|
|
import org.springframework.core.io.ByteArrayResource;
|
import org.springframework.web.multipart.MultipartFile;
|
|
import java.io.File;
|
import java.io.IOException;
|
import java.io.InputStream;
|
import java.nio.file.Files;
|
import java.nio.file.Path;
|
import java.nio.file.Paths;
|
|
public class FileUtils {
|
|
public static MultipartFile convertFileToMultipartFile(String filePath) throws IOException {
|
Path path = Paths.get(filePath);
|
String fileName = path.getFileName().toString();
|
byte[] fileContent = Files.readAllBytes(path);
|
ByteArrayResource resource = new ByteArrayResource(fileContent);
|
|
return new CustomMultipartFile(resource, fileName);
|
}
|
|
private static class CustomMultipartFile implements MultipartFile {
|
|
private final ByteArrayResource resource;
|
private final String fileName;
|
|
public CustomMultipartFile(ByteArrayResource resource, String fileName) {
|
this.resource = resource;
|
this.fileName = fileName;
|
}
|
|
@Override
|
public String getName() {
|
return null;
|
}
|
|
@Override
|
public String getOriginalFilename() {
|
return fileName;
|
}
|
|
@Override
|
public String getContentType() {
|
return null;
|
}
|
|
@Override
|
public boolean isEmpty() {
|
return false;
|
}
|
|
@Override
|
public long getSize() {
|
return resource.contentLength();
|
}
|
|
@Override
|
public byte[] getBytes() throws IOException {
|
return resource.getByteArray();
|
}
|
|
@Override
|
public InputStream getInputStream() throws IOException {
|
return resource.getInputStream();
|
}
|
|
@Override
|
public void transferTo(File dest) throws IOException, IllegalStateException {
|
Files.copy(resource.getInputStream(), dest.toPath());
|
}
|
}
|
}
|