我在文件系统中上传文件时遇到一些问题,上传文件后没有格式。例如,如果我上传 .doc 格式的文件,上传后它的名字中没有任何结尾。
这是上传文件的方法
@RequestMapping(value = "/uploadingPageFileForDeputeAppeal", method = RequestMethod.POST)
public String uploadFile(@RequestParam("file") MultipartFile file,
@RequestParam("name") String name,
@RequestParam(value = "id", required = true) int id,
Model model){
LOGGER.debug("Receive request to add file");
if(!file.isEmpty()){
try {
byte [] bytes = file.getBytes();
//Creating the directory to store file
String path = System.getProperty("user.home");
File directory = new File(path + File.separator + "DeputeAppealsFiles");
if(!directory.exists())
directory.mkdirs();
// Create the file on server
File serverFile = new File(directory.getAbsolutePath() + File.separator + name);
BufferedOutputStream stream = new BufferedOutputStream(
new FileOutputStream(serverFile));
stream.write(bytes);
stream.close();
DeputeAppeal deputeAppeal = deputeAppealService.getById(id);
deputeAppealService.editFilePath(deputeAppeal, serverFile.getAbsolutePath());
model.addAttribute("deputeAppealId", deputeAppeal);
} catch (Exception e) {
return "You failed to upload " + file.getName() + " => " + e.getMessage();
}
} else {
return "You failed to upload " + file.getName()
+ " because the file was empty.";
}
return "deputeAppealView/addedFile";
}
有什么想法吗?这很麻烦,因为上传文件后我需要获取带有标签的文件,并且我认为我无法获取它,因为文件路径保存时没有格式,并且我无法在文件系统中获取它
最佳答案
您使用 @RequestParam("name") String name
中的名称保存文件,因此您应该知道在那里传递的内容。
如果您不想传递带扩展名的名称,可以从 MultipartFile 获取它。你可以这样做:
file.getOriginalFilename().split("\\.")[1]; // it will fail, if there is no extension, so you should add error handling
或根据内容类型查找:
file.getContentType();
关于java - 在Ubuntu文件系统中上传文件后,文件没有格式,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/38466341/