SpringMVC的文件上傳需要注意的問題

簡要的代碼羅列

1、需要的jar包

<!-- https://mvnrepository.com/artifact/commons-io/commons-io -->
    <dependency>
        <groupId>commons-io</groupId>
        <artifactId>commons-io</artifactId>
        <version>2.4</version>
    </dependency>

    <!-- https://mvnrepository.com/artifact/commons-fileupload/commons-fileupload -->
    <dependency>
        <groupId>commons-fileupload</groupId>
        <artifactId>commons-fileupload</artifactId>
        <version>1.3.1</version>
    </dependency>

2、dispatcher-servlet.xml

<!--需要添加bean-->
<bean id="multipartResolver" class="org.springframework.web.multipart.commons.CommonsMultipartResolver">
        <property name="maxUploadSize" value="209715200"/>
        <property name="defaultEncoding" value="UTF-8"/>
        <property name="resolveLazily" value="true"/>
</bean>

3、Controller

@RequestMapping(value="/doUpload",method=RequestMethod.POST)
    public String doUploadFile(@RequestParam("file") MultipartFile file) throws IOException{
        if(!file.isEmpty()){
            FileUtils.copyInputStreamToFile(file.getInputStream(),new File("E:\\temp\\",System.currentTimeMillis()+file.getOriginalFilename()));
        }
        return "success";
    }

5、upload.jsp

<form action="<%=request.getContextPath()%>/hello/doUpload" method="post" enctype="multipart/form-data">
        <input type="file" name="file">
        <input type="submit">
    </form>

注意: jsp文件中enctype屬性需要寫,不然會報以下的錯
這裏寫圖片描述
這裏的坑我查了很久,需要很注意!!!!

發佈了24 篇原創文章 · 獲贊 4 · 訪問量 2萬+
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章