springmvc實現(xiàn)文件上傳功能
更新時間:2021年03月16日 16:35:55 作者:愛吃番茄的小狐貍
這篇文章主要為大家詳細介紹了springmvc實現(xiàn)文件上傳功能,文中示例代碼介紹的非常詳細,具有一定的參考價值,感興趣的小伙伴們可以參考一下
一個簡單的springmvc文件上傳例子
所需的依賴
只需要這個就好了。在idea的依賴關(guān)系圖中,commons-fileupload包含了commons-io依賴

<dependency> <groupId>commons-fileupload</groupId> <artifactId>commons-fileupload</artifactId> <version>1.3.2</version> </dependency>
一個簡單的文件上傳的頁面
<form action="http://localhost:8080/springmvc_Web_exploded/fff" method="post" enctype="multipart/form-data"> <input type="file" name="file" id="filer_input" multiple="multiple"> <input type="submit" value="Submit"> </form>
在spring的配置文件中注入一個文件上傳的bean
spring.xml
<!-- 文件上傳的bean--> <bean id="multipartResolver" class="org.springframework.web.multipart.commons.CommonsMultipartResolver"> <!--上傳文件的最大大小,單位為字節(jié) --> <property name="maxUploadSize" value="17367648787"></property> <!-- 上傳文件的編碼 --> <property name="defaultEncoding" value="UTF-8"></property> </bean>
實例代碼
@PostMapping("/fff")
public String file(@PathVariable("file")MultipartFile file, HttpServletRequest req) throws IOException {
//判斷文件不存在
if (file.isEmpty()){
return "faile.html";
}
//我想放到這個地方文件的路徑
String realPath = req.getServletContext().getRealPath("/WEB-INF/file");
//返回客戶端文件系統(tǒng)中的原始文件名
String filename = file.getOriginalFilename();
File myFile = new File(realPath, filename);
if (!myFile.getParentFile().exists()){
myFile.getParentFile().mkdir();
System.out.println("文件夾被創(chuàng)建了");
}
//將前端傳過來的文件,傳到自己new的File對象中
file.transferTo(myFile);
return "success.html";
}
注意事項:
1、文件上傳請求必須用post請求。
2、注意路徑問題
3、前端的form表單必須添加 enctype="multipart/form-data" 這個屬性
以上就是本文的全部內(nèi)容,希望對大家的學(xué)習(xí)有所幫助,也希望大家多多支持腳本之家。
相關(guān)文章
Java并發(fā)編程深入理解之Synchronized的使用及底層原理詳解 下
在并發(fā)編程中存在線程安全問題,主要原因有:1.存在共享數(shù)據(jù) 2.多線程共同操作共享數(shù)據(jù)。關(guān)鍵字synchronized可以保證在同一時刻,只有一個線程可以執(zhí)行某個方法或某個代碼塊,同時synchronized可以保證一個線程的變化可見(可見性),即可以代替volatile2021-09-09
SpringAOP 構(gòu)造注入的實現(xiàn)步驟
這篇文章主要介紹了SpringAOP_構(gòu)造注入的實現(xiàn)步驟,幫助大家更好的理解和學(xué)習(xí)使用spring框架,感興趣的朋友可以了解下2021-05-05

