1. 程式人生 > 實用技巧 >SpringMvc第五篇【上傳檔案】

SpringMvc第五篇【上傳檔案】

  1. 編寫jsp
<%--
  Created by IntelliJ IDEA.
  User: 60434
  Date: 2020/8/26
  Time: 10:40
  To change this template use File | Settings | File Templates.
--%>
<%@ page contentType="text/html;charset=UTF-8" language="java" %>
<html>
<head>
    <title>Title</title>
</head>
<body>

<form method="post" action="${pageContext.request.contextPath}/request9" enctype="multipart/form-data">
    <input type="file" name="multipartFile"><br/> <!--name="multipartFile"中的multipartFile要和Controller中的形參一致-->
    <input type="file" name="multipartFile"><br/>
    <input type="submit" value="提交">
</form>

</body>
</html>
  1. 匯入座標
        <dependency>
            <groupId>commons-fileupload</groupId>
            <artifactId>commons-fileupload</artifactId>
            <version>1.4</version>
        </dependency>
        <dependency>
            <groupId>commons-io</groupId>
            <artifactId>commons-io</artifactId>
            <version>2.4</version>
        </dependency>
  1. 配置上傳檔案解析器
    <!--配置檔案上傳解析器-->
    <!--id只能是multipartResolver-->
    <bean id="multipartResolver" class="org.springframework.web.multipart.commons.CommonsMultipartResolver">
        <!--上傳檔案的編碼型別-->
        <property name="defaultEncoding" value="UTF-8"/>
        <!--上傳檔案總大小-->
        <property name="maxUploadSize" value="524800"/>
        <!--上傳單個檔案的大小-->
        <property name="maxUploadSizePerFile" value="524800"/>
    </bean>
  1. 編寫Controller
    @RequestMapping("/request9")
    public void request9(MultipartFile[] multipartFile, HttpServletRequest httpServletRequest) throws IOException {
        for (MultipartFile file : multipartFile) {
            file.transferTo(new File("F:/ProjectTest/fileupload/"+file.getOriginalFilename()));
        }
    }