在看《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的路徑,因此書上的代碼:
@Override
protected void customizeRegistration(Dynamic registration) {
registration.setMultipartConfig(
new MultipartConfigElement("/tmp/uploads")
);
}
也只是在本地tomcat服務器的根路徑下創建/tmp/uploads,此時本地服務器並沒有這個目錄,因此報錯。
解決方法
1.使用絕對路徑
2.修改location的值
這個location可以理解爲臨時文件目錄,我們可以通過配置location的值,使其指向我們的項目路徑,這樣就解決了我們遇到的問題。代碼如下:
@Override
protected void customizeRegistration(Dynamic registration) {
registration.setMultipartConfig(
new MultipartConfigElement("/home/hg_yi/Web項目/spittr/web")
);
}
profilePicture.write("/tmp/uploads" + profilePicture.getSubmittedFileName());
這樣就解決錯誤啦~~