我想保存上传的图片到特定文件夹中部署Tomcat上弹簧3 MVC应用程序
我的问题是我不能上传的图片文件保存到其中applciation运行的主机。
这里是我的尝试:
private void saveFile(MultipartFile multipartFile, int id) throws Exception {
String destination = "/images/" + id + "/" + multipartFile.getOriginalFilename();
File file = new File(destination);
multipartFile.transferTo(file);
}
结果:FileNotFoundException异常 - 是肯定的,我确实想要创建这个文件!?!
我试图使用它的context.getRealPath
或getResources("destination")
,但没有成功。
如何创建在我和我的多文件的内容应用的特定文件夹中的新文件?
此代码一定会帮助你的。
String filePath = request.getServletContext().getRealPath("/");
multipartFile.transferTo(new File(filePath));
让我们创建Web应用程序中的上传目录并保存在Web应用程序/上传文件:
@RestController
public class GreetingController {
private final static Logger log = LoggerFactory.getLogger(GreetingController.class);
@Autowired
private HttpServletRequest request;
@RequestMapping(value = "/uploadfile", method = RequestMethod.POST)
public
@ResponseBody
ResponseEntity handleFileUpload(@RequestParam("file") MultipartFile file) {
if (!file.isEmpty()) {
try {
String uploadsDir = "/uploads/";
String realPathtoUploads = request.getServletContext().getRealPath(uploadsDir);
if(! new File(realPathtoUploads).exists())
{
new File(realPathtoUploads).mkdir();
}
log.info("realPathtoUploads = {}", realPathtoUploads);
String orgName = file.getOriginalFilename();
String filePath = realPathtoUploads + orgName;
File dest = new File(filePath);
file.transferTo(dest);
编码
String realPathtoUploads = request.getServletContext().getRealPath(uploadsDir);
如果我从理念IDE中运行应用程序返回我一个路径
C:\Users\Iuliia\IdeaProjects\ENumbersBackend\src\main\webapp\uploads\
旁边的路径,如果我做的.war和Tomcat下运行它:
D:\Programs_Files\apache-tomcat-8.0.27\webapps\enumbservice-0.2.0\uploads\
我看到了一个弹簧3例如使用XML配置(注意这个春天4.2不起作用。*):qazxsw POI`
<bean id="multipartResolver"
class="org.springframework.web.multipart.commons.CommonsMultipartResolver">
<property name="maxUploadSize" value="100000" />
<property name="uploadTempDir" ref="uploadDirResource" />
</bean>
<bean id="uploadDirResource" class="org.springframework.core.io.FileSystemResource">
<constructor-arg>
<value>C:/test111</value>
</constructor-arg>
</bean>
这是如何让应用程序在春天的真实路径(未使用的响应,会话...)
以下为我工作在Ubuntu:
String ApplicationPath =
ContextLoader.getCurrentWebApplicationContext().getServletContext().getRealPath("");
你可以从multipartfile InputStream并将其复制到任何你想要的目录。
String filePath = request.getServletContext().getRealPath("/");
File f1 = new File(filePath+"/"+multipartFile.getOriginalFilename());
multipartFile.transferTo(f1);
这适用于Linux和Windows。