SpringMVC文件上傳

一、 導入依賴

<!-- 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>
代碼實現

二、 配置spring-mvc.xml

<!--文件上傳解析器-->
<bean id="multipartResolver" class="org.springframework.web.multipart.commons.CommonsMultipartResolver">
    <!--文件上傳的字符集-->
    <property name="defaultEncoding" value="UTF-8"></property>
    <!--文件的總大小-->
    <property name="maxUploadSize" value="50000000"></property>
    <!--單個文件的大小-->
    <property name="maxUploadSizePerFile" value="500000"></property>
</bean>
代碼實現

三、 index.jsp

<%@ page contentType="text/html;charset=UTF-8" language="java" %>
<html>
<head>
    <title>文件上傳案例</title>
</head>
<body>
    <form action="/file/uploadOne" method="post" enctype="multipart/form-data">
        <input type="file" name="upload"/><br/>
        <input type="submit" value="提交"/>
    </form>
</body>
</html>
代碼實現

四、FileuploadController

@Controller
@RequestMapping("/file")
public class FileuploadController {

    /**
     * 單文件上傳
     * @param upload
     * @param session
     * @return
     * @throws IOException
     */
    @RequestMapping("/uploadOne")
    public String fileuploadOne(MultipartFile upload, HttpSession session) throws IOException {
        //獲取絕對路徑
        String realPath = session.getServletContext().getRealPath("/upload");
        //獲取文件上傳提交的文件名
        String filename = upload.getOriginalFilename();
        System.out.println(filename);
        //組合路徑+上傳操做
        upload.transferTo(new File(realPath,filename));
        return "success";
    }

}
代碼實現

五、webapp中建立upload文件夾

六、效果

  

   

相關文章
相關標籤/搜索