SpringMVC 通過commons-fileupload實現檔案上傳
阿新 • • 發佈:2021-01-31
[TOC](目錄)
# 配置
## web.xml
```xml
```
## SpringMVC配置檔案 applicationContext.xml 上傳檔案的核心配置類:CommonsMultipartResolver,注意`id="multipartResolver"`不要寫錯 ```xml ```
# 檔案上傳 Controller ## 上傳實現一 ```java package com.pro.controller; import org.springframework.web.bind.annotation.RequestMapping; import org.springframework.web.bind.annotation.RequestParam; import org.springframework.web.bind.annotation.RestController; import org.springframework.web.multipart.commons.CommonsMultipartFile; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse; import java.io.*; import java.net.URLEncoder; import java.util.HashMap; import java.util.Map; @RestController public class FileController { /* * 採用file.transferTo 來儲存上傳的檔案 */ @RequestMapping("/upload2") public Map fileUpload2(@RequestParam("file") CommonsMultipartFile file, HttpServletRequest request) throws IOException { //上傳路徑儲存設定 String path = request.getServletContext().getRealPath("/upload"); File realPath = new File(path); if (!realPath.exists()){ realPath.mkdir(); } //上傳檔案地址 System.out.println("上傳檔案儲存地址 --> "+realPath); //通過CommonsMultipartFile的方法直接寫檔案(注意這個時候) file.transferTo(new File(realPath +"/"+ file.getOriginalFilename()));
## SpringMVC配置檔案 applicationContext.xml 上傳檔案的核心配置類:CommonsMultipartResolver,注意`id="multipartResolver"`不要寫錯 ```xml ```
# 檔案上傳 Controller ## 上傳實現一 ```java package com.pro.controller; import org.springframework.web.bind.annotation.RequestMapping; import org.springframework.web.bind.annotation.RequestParam; import org.springframework.web.bind.annotation.RestController; import org.springframework.web.multipart.commons.CommonsMultipartFile; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse; import java.io.*; import java.net.URLEncoder; import java.util.HashMap; import java.util.Map; @RestController public class FileController { /* * 採用file.transferTo 來儲存上傳的檔案 */ @RequestMapping("/upload2") public Map fileUpload2(@RequestParam("file") CommonsMultipartFile file, HttpServletRequest request) throws IOException { //上傳路徑儲存設定 String path = request.getServletContext().getRealPath("/upload"); File realPath = new File(path); if (!realPath.exists()){ realPath.mkdir(); } //上傳檔案地址 System.out.println("上傳檔案儲存地址 --> "+realPath); //通過CommonsMultipartFile的方法直接寫檔案(注意這個時候) file.transferTo(new File(realPath +"/"+ file.getOriginalFilename()));