1. 程式人生 > >springmvc檔案上傳注意事項

springmvc檔案上傳注意事項

最近開發springmvc檔案上傳的功能遇到幾個問題,這裡記錄下

1,java.lang.ClassNotFoundException: org.apache.commons.fileupload.FileItemFactory

錯誤原因:缺少jar包依賴新增
解決辦法:POM中新增依賴

<dependency>
            <groupId>commons-fileupload</groupId>
            <artifactId>commons-fileupload</artifactId>
            <version>${fileupload-version}</version>
        </dependency>
        <dependency>
            <groupId>commons-io</groupId>
            <artifactId>commons-io</artifactId>
            <version>${io-version}</version>
        </dependency>
2,Failedtoconvert value of type [java.lang.String] to required type [org.springframework.web.multipart.MultipartFile];
nested exception is java.lang.IllegalStateException: Cannot convert value of type [java.lang.String] to required type

[org.springframework.web.multipart.MultipartFile]: no matching editors or conversion strategy found

錯誤原因:get方式提交
解決辦法:controller上加method,form表單新增 method

@RequestMapping(value = "/upload",method = { RequestMethod.POST })
method="post"

3,springmvc引入靜態檔案404問題

原因:配置dispather後,所有的請求都通過spring,但是並沒有處理*/jquery.js的controller,所以404

解決辦法:web.xml新增如下程式碼(必須在dispather配置之前):

<servlet-mapping>
        <servlet-name>default</servlet-name>
        <url-pattern>*.jpg</url-pattern>
    </servlet-mapping>
    <servlet-mapping>
        <servlet-name>default</servlet-name>
        <url-pattern>*.js</url-pattern>
    </servlet-mapping>
    <servlet-mapping>
        <servlet-name>default</servlet-name>
        <url-pattern>*.css</url-pattern>
    </servlet-mapping>
還有一種解決辦法:mvc.xml中新增如下程式碼
<mvc:resources mapping="/js/**" location="/js/" />