一、匯入相關依賴
<dependencies> <!--檔案上傳--> <dependency> <groupId>commons-fileupload</groupId> <artifactId>commons-fileupload</artifactId> <version>1.4</version> </dependency> </dependencies>
實際上我們需要的包有commons-fileupload和commons-io,但我們使用Maven時匯入commons-fileupload包,Maven會自動幫我們匯入它的依賴包commons-io,
二、前端建立一個檔案上傳的表單
<form action="${pageContext.request.contextPath}/upload" method="post" enctype="multipart/form-data"> <input type="file" accept="image/*" name="file"/> <input type="submit" value="上傳檔案"/> </form>
enctype時設定被提交資料的編碼,enctype="multipart/form-data"是設定檔案以二進制資料發送給服務器,
<input type="file" accept="image/*"> type="file"說明是要選擇檔案進行上傳,accept="image/*"表示上傳檔案的MIME型別,這里表示的是各種型別的圖片檔案,
三、SpringMVC中配置MultipartResolver
SpringMVC能夠支持檔案上傳的操作,但是需要在背景關系中對MultipartResolver進行配置,具體配置如下:
<!--檔案上傳--> <bean class="org.springframework.web.multipart.commons.CommonsMultipartResolver" id="multipartResolver"> <!--請求的編碼格式,默認為ISO-8859-1--> <property name="defaultEncoding" value="utf-8"/> <!-- 上傳檔案大小上限,單位為位元組(byte),這里是10M和40K 第二個其實是一個閾值,小于此值檔案會存在記憶體中,大于此值檔案會存在磁盤上,所以理解成上傳檔案的最小上限沒有問題 --> <property name="maxUploadSize" value="10485760"/> <property name="maxInMemorySize" value="40960"/> </bean>
四、撰寫檔案上傳的controller,這里有兩種上傳方法
方法一:
@RequestMapping("/upload")
@ResponseBody
public String fileUpload(@RequestParam("file") CommonsMultipartFile file , HttpServletRequest request) throws IOException {
//上傳的檔案名
String uploadFileName = file.getOriginalFilename();
//判斷檔案名是否為空
if ("".equals(uploadFileName)){
return null;
}
//上傳路徑保存設定
String path = request.getServletContext().getRealPath("/upload");
//如果路徑不存在,創建一個
File realPath = new File(path);
if (!realPath.exists()){
realPath.mkdir();
}
InputStream is = file.getInputStream(); //檔案輸入流
OutputStream os = new FileOutputStream(new File(realPath,uploadFileName)); //檔案輸出流
//讀取寫出
int len=0;
byte[] buffer = new byte[1024];
while ((len=is.read(buffer))!=-1){
os.write(buffer,0,len);
os.flush();
}
os.close();
is.close();
return "/upload/" + uploadFileName;
}
方法二:
@RequestMapping("/upload2")
@ResponseBody
public String 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();
}
//上傳的檔案名
String uploadFileName = file.getOriginalFilename();
//通過CommonsMultipartFile的方法直接寫檔案(
file.transferTo(new File(realPath +"/"+ uploadFileName));
return "/upload/" + uploadFileName;
}
注意: 這里如果上傳路徑保存設定是多級目錄,就需要用File.mkdirs(),
(本文僅作個人學習記錄用,如有紕漏敬請指正)
轉載請註明出處,本文鏈接:https://www.uj5u.com/houduan/519028.html
標籤:其他
上一篇:C++基礎
下一篇:c++物件的拷貝、構造、虛構
