我正在使用spring boot构建项目,我想将图像上传到服务器(在我的本地服务器上)。
上传文件的代码是:
@Controller
@RequestMapping("/api/v1")
public class ImageController {
@RequestMapping(value="/upload", method=RequestMethod.GET)
public @ResponseBody String provideUploadInfo() {
return "You can upload a file by posting to this same URL.";
}
@RequestMapping(value="/upload", method=RequestMethod.POST)
public @ResponseBody String handleFileUpload(@RequestParam("name") String name,@RequestParam("email") String email,
@RequestParam("file") MultipartFile file){
if (!file.isEmpty()) {
BufferedImage src;
try {
src = ImageIO.read(new ByteArrayInputStream(file.getBytes()));
File destination = new File("/"+System.getProperty("user.home")+"/samepinchbucket/"+email+"/pics/");
ImageIO.write(src, "png", destination);
//Save the id you have used to create the file name in the DB. You can retrieve the image in future with the ID.
return "You successfully uploaded " + name + "!";
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
return "You failed to upload " + name + " => " + e.getMessage();
}
}else{
return "You failed to upload " + name + " because the file was empty.";
}
}
}
此代码工作正常,但图片正在myfolder
上传,pics
作为图片名称,但我的要求是图片应上传到pics
文件夹中而不是{{1} }}
答案 0 :(得分:1)
您应该只使用不同的File
构造函数,例如
String folder = "/"+System.getProperty("user.home")+ "/samepinchbucket/"+email+"/pics/";
File destination = new File(folder, file.getOriginalFilename());
这会将文件存储在原始文件名
下的文件夹pics
中
答案 1 :(得分:0)
从您的代码中,您似乎正在使用一些带有Spring的Java Web服务器。
假设getImageDirPath()
方法返回相对于tomcat服务器主目录的imagePath
:
private static String getImageDirPath(String email) {
String envVal = null;
String rootPath = System.getProperty("catalina.home");
File dir = new File(rootPath + File.separator + "samepinchbucket" + File.separator +
email+File.separator + "pics" + File.separator);
if (!dir.exists())
dir.mkdirs();
return dir.getAbsolutePath() + File.separator;
}