欧美bbbwbbbw肥妇,免费乱码人妻系列日韩,一级黄片

springmvc實(shí)現(xiàn)文件上傳功能

 更新時(shí)間:2021年03月16日 16:35:55   作者:愛吃番茄的小狐貍  
這篇文章主要為大家詳細(xì)介紹了springmvc實(shí)現(xiàn)文件上傳功能,文中示例代碼介紹的非常詳細(xì),具有一定的參考價(jià)值,感興趣的小伙伴們可以參考一下

一個(gè)簡(jiǎn)單的springmvc文件上傳例子

所需的依賴

只需要這個(gè)就好了。在idea的依賴關(guān)系圖中,commons-fileupload包含了commons-io依賴

<dependency>
  <groupId>commons-fileupload</groupId>
  <artifactId>commons-fileupload</artifactId>
  <version>1.3.2</version>
</dependency>

一個(gè)簡(jiǎn)單的文件上傳的頁面

<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的配置文件中注入一個(gè)文件上傳的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>

實(shí)例代碼

@PostMapping("/fff")
 public String file(@PathVariable("file")MultipartFile file, HttpServletRequest req) throws IOException {

 //判斷文件不存在
  if (file.isEmpty()){
   return "faile.html";
  }

  //我想放到這個(gè)地方文件的路徑
  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對(duì)象中
  file.transferTo(myFile);

  return "success.html";
 }

注意事項(xiàng):

1、文件上傳請(qǐng)求必須用post請(qǐng)求。
2、注意路徑問題
3、前端的form表單必須添加 enctype="multipart/form-data" 這個(gè)屬性

以上就是本文的全部內(nèi)容,希望對(duì)大家的學(xué)習(xí)有所幫助,也希望大家多多支持腳本之家。

相關(guān)文章

最新評(píng)論