Spring MVC将上传的MultipartFile保存到特定文件夹 [英] Spring MVC save uploaded MultipartFile to specific folder
问题描述
我想将上传的图像保存到部署在Tomcat上的Spring 3 MVC应用程序中的特定文件夹中
I want to save uploaded images to a specific folder in a Spring 3 MVC application deployed on Tomcat
我的问题是我无法将上传的图像文件保存到运行应用程序的主机上.
My problem is that I cannot save the uploaded images files to the host where the applciation is running.
这是我尝试过的:
private void saveFile(MultipartFile multipartFile, int id) throws Exception {
String destination = "/images/" + id + "/" + multipartFile.getOriginalFilename();
File file = new File(destination);
multipartFile.transferTo(file);
}
结果:FileNotFoundException-是的,我确实要创建此文件!?!
Result: FileNotFoundException - Yes sure, I do want create this file!?!
我使用context.getRealPath
或getResources("destination")
进行了尝试,但没有成功.
I tried it using the context.getRealPath
or getResources("destination")
, but without any success.
如何使用多部分文件的内容在应用程序的特定文件夹中创建一个新文件?
How can I create a new file in a specific folder of my app with the content of my multipart file?
推荐答案
此代码一定会对您有所帮助.
This code will surely help you.
String filePath = request.getServletContext().getRealPath("/");
multipartFile.transferTo(new File(filePath));
这篇关于Spring MVC将上传的MultipartFile保存到特定文件夹的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!