Spring--《Spring实战》The temporary upload location [/tmp/uploads] is not valid

来源:互联网 发布:windows虚拟内存开启 编辑:程序博客网 时间:2024/06/05 10:33

在看《Spring实战》第七章的时候,需要上传文件,书上说的是将上传的图片保存在/tmp/uploads这个目录下,因此我给项目的根路径下创建了/tmp/uploads这个目录,但是却出现了标题中的错误,经过一番斗争之后,明白了问题的所在。


问题分析

要解决这个问题,我们需要看一下Spring的源码:

public class StandardMultipartHttpServletRequest extends AbstractMultipartHttpServletRequest {    //中间代码省略    /**     * Spring MultipartFile adapter, wrapping a Servlet 3.0 Part object.     */    @SuppressWarnings("serial")    private static class StandardMultipartFile implements MultipartFile, Serializable {        //中间代码省略        @Override        public void transferTo(File dest) throws IOException,IllegalStateException {            this.part.write(dest.getPath());        }    }}
package org.apache.catalina.core;/** * Adaptor to allow {@link FileItem} objects generated by the package renamed * commons-upload to be used by the Servlet 3.0 upload API that expects * {@link Part}s. */public class ApplicationPart implements Part {    //中间代码省略    @Override    public void write(String fileName) throws IOException {        File file = new File(fileName);        if (!file.isAbsolute()) {            file = new File(location, fileName);        }        try {            fileItem.write(file);        } catch (Exception e) {            throw new IOException(e);        }    }}

源码一目了然,使用Servlet3.0的支持的上传文件功能时,如果我们没有使用绝对路径的话,transferTo方法会在相对路径前添加一个location路径,即:file = new File(location, fileName);。当然,这也影响了SpringMVC的Multipartfile的使用。

由于我们创建的File在项目路径/tmp/uploads/,而transferTo方法预期写入的文件路径为/etc/tpmcat/work/Catalina/localhost/ROOT/tmp/uploads/,注意此时写入的路径是相对于你本地tomcat的路径,因此书上的代码:

@Overrideprotected void customizeRegistration(Dynamic registration) {    registration.setMultipartConfig(        new MultipartConfigElement("/tmp/uploads")    );}

也只是在本地tomcat服务器的根路径下创建/tmp/uploads,此时本地服务器并没有这个目录,因此报错。


解决方法

1.使用绝对路径

2.修改location的值
这个location可以理解为临时文件目录,我们可以通过配置location的值,使其指向我们的项目路径,这样就解决了我们遇到的问题。代码如下:

@Overrideprotected void customizeRegistration(Dynamic registration) {    registration.setMultipartConfig(        new MultipartConfigElement("/home/hg_yi/Web项目/spittr/web")    );}
profilePicture.write("/tmp/uploads" + profilePicture.getSubmittedFileName());

这样就解决错误啦~~

阅读全文
0 0
原创粉丝点击