我有这样的项目结构,资源目录。这一次,我有这样的代码:保存文件使用Spring
public String fileUpload(UploadedFile uploadedFile) {
InputStream inputStream = null;
OutputStream outputStream = null;
MultipartFile file = uploadedFile.getFile();
String fileName = file.getOriginalFilename();
File newFile = new File("/res/img/" + fileName);
try {
inputStream = file.getInputStream();
if (!newFile.exists()) {
newFile.createNewFile();
}
outputStream = new FileOutputStream(newFile);
int read = 0;
byte[] bytes = new byte[1024];
while ((read = inputStream.read(bytes)) != -1) {
outputStream.write(bytes, 0, read);
}
} catch (IOException e) {
e.printStackTrace();
}
return newFile.getAbsolutePath();
}
但将文件保存到user.dir
目录,这是~/Work/Tomcat/bin/
。 那么我怎样才能将文件上传到res
目录?
不要在那里上传文件。选择一个专用于该目录的单独目录。 –
@SotiriosDelimanolis为什么'res'目录不合适? –
首先,因为它不一定存在。 'Servlet'容器可能选择不扩展你的'.war'。 –