我正在尝试更改 MultipartFile 的名称。
我在控制器上使用 MultipartFile 来调用休息服务:
@PostMapping("/post")
public ResponseEntity<String> handleFileUpload(@RequestParam("file") MultipartFile file)
{
...
}
您对更改上传文件的 OriginalFilename 有什么想法吗?
非常感谢。
您可以尝试以下代码。
@PostMapping("/post")
public ResponseEntity<String> handleFileUpload(@RequestParam("file") MultipartFile file)
{
try {
String filename = "random_filename.pdf"; // Give a random filename here.
byte[] bytes = file.getBytes();
String insPath = <DIRECTORY PATH> + filename // Directory path where you want to save ;
Files.write(Paths.get(insPath), bytes);
return ResponseEntity.ok(filename);
}
catch (IOException e) {
// Handle exception here
}
}
您必须记住在文件名中添加随机字符串。如果你只是硬编码文件名,那么每次上传文件时,之前的文件都会被替换。
您可以通过如下方式实现文件重命名。要验证,请转到 uploadDir,您将获得一个带有
"renameTest"
的文件。
您可以将
clientId + uploadTime
附加到文件名以避免数据库中出现相同的文件名
@PostMapping(value = "/post")
public String renameMultipartFile(@RequestParam("file") MultipartFile file) {
String uploadDir = "yourPath";
String filename = "renameTest";
Path saveTO = Paths.get(uploadDir + filename);
try {
try {
Files.copy(file.getInputStream(), saveTO);
} catch (Exception e) {
e.printStackTrace();
throw new RuntimeException("Error : " + e.getMessage());
}
return "File uploaded successfully";
} catch (Exception e) {
e.printStackTrace();
return "Error : " + e.getMessage();
}
}
如果您将文件“转发”到另一台服务器,您可以尝试以下代码:
import jakarta.validation.constraints.NotNull;
import org.springframework.core.io.Resource;
import org.springframework.lang.Nullable;
import java.io.File;
import java.io.IOException;
import java.io.InputStream;
import java.net.URI;
import java.net.URL;
import java.nio.channels.ReadableByteChannel;
import java.nio.charset.Charset;
public class MultipartFileResourceNameDecorator implements Resource {
private final Resource resource;
private final String newFileName;
public MultipartFileResourceNameDecorator(@NotNull Resource resource, @NotNull String newFileName) {
this.resource = resource;
this.newFileName = newFileName;
}
@Override
@Nullable
public String getFilename() {
return newFileName;
}
// delegate another methods
}
来电者:
private String sendByFile(Resource fileResource, String newFileName) {
var resource = new MultipartFileResourceNameDecorator(fileResource, newFileName);
log.info("Upload file: {}", resource.getFilename());
try {
HttpHeaders headers = new HttpHeaders();
headers.setContentType(MediaType.MULTIPART_FORM_DATA);
// Create the request body with the file
var body = new LinkedMultiValueMap<String, Object>();
body.add("file", resource);
// Create the HttpEntity
var entity = new HttpEntity<>(body, headers);
// Make the POST request
var response = restTemplate.postForEntity(urlUpload, entity, String.class);
// Your logic here with response
} catch (Exception e) {
log.error("Upload fail", e);
return null;
}
}