我想将上传的文件存储在我指定的文件夹中,如下所示:
/SpringMVC/tmp
但它存储在此文件夹中:
C:\Users\zhanzhex\eclipse-workspace\.metadata\.plugins\org.eclipse.wst.server.core\tmp0\work\Catalina\localhost\SpringMVC\tmp\spittr\uploads
这是我处理上传的控制器方法:
@RequestMapping(value="/register", method=RequestMethod.POST)
public String processRegistration(
@RequestPart(name="profilePicture",required=false) Part profilePicture,
@Valid Spitter spitter, Errors errors) throws IOException
{
if (errors.hasErrors())
{
System.out.println("find errors");
return "registerForm";
}
profilePicture.write(spitter.getId() + "_profile." + profilePicture.getSubmittedFileName().substring(profilePicture.getSubmittedFileName().indexOf(".") + 1));
spitterRespository.saveSpitter(spitter);
return "redirect:/spitter/"+spitter.getId();
}
我只是在我的/tmp/spittr/uploads
中配置文件上传的临时文件夹(web.xml
),但我想在控制器方法中调用write方法时更改文件夹,似乎我不能。如果我像这样调用write方法:
profilePicture.write("/tmp/spittr/uploads/" + spitter.getId() + "_profile.jpg");
它将抛出IOException以指示该文件夹不存在:
C:\Users\zhanzhex\eclipse-workspace\.metadata\.plugins\org.eclipse.wst.server.core\tmp0\work\Catalina\localhost\SpringMVC\tmp\spittr\uploads\tmp\spittr\uploads
所以,我必须删除前缀" / tmp / spittr / uploads"当我调用profilePicture.write方法时。
请参阅下面的 web.xml :
<?xml version="1.0" encoding="UTF-8"?>
<web-app xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xmlns="http://java.sun.com/xml/ns/javaee"
xsi:schemaLocation="http://java.sun.com/xml/ns/javaee http://java.sun.com/xml/ns/javaee/web-app_3_0.xsd"
id="WebApp_ID" version="3.0">
<display-name>SpringMVCs</display-name>
<context-param>
<param-name>contextClass</param-name>
<param-value>org.springframework.web.context.support.AnnotationConfigWebApplicationContext</param-value>
</context-param>
<context-param>
<param-name>contextConfigLocation</param-name>
<param-value>spittr.config.RootConfig</param-value>
</context-param>
<listener>
<listener-class>
org.springframework.web.context.ContextLoaderListener
</listener-class>
</listener>
<servlet>
<servlet-name>spittrAppServlet</servlet-name>
<servlet-class>
org.springframework.web.servlet.DispatcherServlet
</servlet-class>
<init-param>
<param-name>contextClass</param-name>
<param-value>org.springframework.web.context.support.AnnotationConfigWebApplicationContext</param-value>
</init-param>
<init-param>
<param-name>contextConfigLocation</param-name>
<param-value>spittr.config.WebConfig</param-value>
</init-param>
<load-on-startup>1</load-on-startup>
<multipart-config>
<location>/tmp/spittr/uploads</location>
<max-file-size>2097152</max-file-size>
<max-request-size>4194304</max-request-size>
</multipart-config>
</servlet>
<servlet-mapping>
<servlet-name>spittrAppServlet</servlet-name>
<url-pattern>/</url-pattern>
</servlet-mapping>
</web-app>
我不知道为什么,我可以更改目标文件夹设置吗?怎么做?
答案 0 :(得分:0)
您可以使用MultipartFile或FilePart接口
代替Part@RequestPart(name="profilePicture",required=false) MultipartFile profilePicture
这些接口公开.transferTo()函数将数据复制到您可以使用的文件,如
profilePicture.transferTo(new File("/path/to/file"));