溫馨提示×

溫馨提示×

您好,登錄后才能下訂單哦!

密碼登錄×
登錄注冊×
其他方式登錄
點(diǎn)擊 登錄注冊 即表示同意《億速云用戶服務(wù)條款》

Spring mvc中怎么實(shí)現(xiàn)文件上傳下載功能

發(fā)布時(shí)間:2021-06-16 14:37:39 來源:億速云 閱讀:134 作者:Leah 欄目:編程語言

這篇文章將為大家詳細(xì)講解有關(guān)Spring mvc中怎么實(shí)現(xiàn)文件上傳下載功能,文章內(nèi)容質(zhì)量較高,因此小編分享給大家做個(gè)參考,希望大家閱讀完這篇文章后對相關(guān)知識有一定的了解。

文件上傳是項(xiàng)目開發(fā)中最常見的功能之一 ,springMVC 可以很好的支持文件上傳,但是SpringMVC上下文中默認(rèn)沒有裝配MultipartResolver,因此默認(rèn)情況下其不能處理文件上傳工作。如果想使用Spring的文件上傳功能,則需要在上下文中配置MultipartResolver。

前端表單要求:為了能上傳文件,必須將表單的method設(shè)置為POST,并將enctype設(shè)置為multipart/form-data。只有在這樣的情況下,瀏覽器才會(huì)把用戶選擇的文件以二進(jìn)制數(shù)據(jù)發(fā)送給服務(wù)器;

對表單中的 enctype 屬性做個(gè)詳細(xì)的說明:

application/x-www=form-urlencoded:默認(rèn)方式,只處理表單域中的 value 屬性值,采用這種編碼方式的表單會(huì)將表單域中的值處理成 URL 編碼方式。

multipart/form-data:這種編碼方式會(huì)以二進(jìn)制流的方式來處理表單數(shù)據(jù),這種編碼方式會(huì)把文件域指定文件的內(nèi)容也封裝到請求參數(shù)中,不會(huì)對字符編碼。

text/plain:除了把空格轉(zhuǎn)換為 "+" 號外,其他字符都不做編碼處理,這種方式適用直接通過表單發(fā)送郵件。

<form action="" enctype="multipart/form-data" method="post">
  <input type="file" name="file"/>
  <input type="submit">
</form>

一旦設(shè)置了enctype為multipart/form-data,瀏覽器即會(huì)采用二進(jìn)制流的方式來處理表單數(shù)據(jù),而對于文件上傳的處理則涉及在服務(wù)器端解析原始的HTTP響應(yīng)。在2003年,Apache Software Foundation發(fā)布了開源的Commons FileUpload組件,其很快成為Servlet/JSP程序員上傳文件的最佳選擇。

Servlet3.0規(guī)范已經(jīng)提供方法來處理文件上傳,但這種上傳需要在Servlet中完成。

而Spring MVC則提供了更簡單的封裝。

Spring MVC為文件上傳提供了直接的支持,這種支持是用即插即用的MultipartResolver實(shí)現(xiàn)的。

Spring MVC使用Apache Commons FileUpload技術(shù)實(shí)現(xiàn)了一個(gè)MultipartResolver實(shí)現(xiàn)類:CommonsMultipartResolver。因此,==SpringMVC的文件上傳還需要依賴Apache Commons FileUpload的組件==。
文件上傳

1、導(dǎo)入文件上傳的jar包,commons-fileupload , Maven會(huì)自動(dòng)幫我們導(dǎo)入他的依賴包 commons-io包;

<!--文件上傳-->
<dependency>
  <groupId>commons-fileupload</groupId>
  <artifactId>commons-fileupload</artifactId>
  <version>1.3.3</version>
</dependency>
<!--servlet-api導(dǎo)入高版本的-->
<dependency>
  <groupId>javax.servlet</groupId>
  <artifactId>javax.servlet-api</artifactId>
  <version>4.0.1</version>
</dependency>

2、配置bean:multipartResolver

【注意?。?!這個(gè)bena的id必須為:multipartResolver , 否則上傳文件會(huì)報(bào)400的錯(cuò)誤!在這里栽過坑,教訓(xùn)!】

<!--文件上傳配置-->
<bean id="multipartResolver" class="org.springframework.web.multipart.commons.CommonsMultipartResolver">
  <!-- 請求的編碼格式,必須和jSP的pageEncoding屬性一致,以便正確讀取表單的內(nèi)容,默認(rèn)為ISO-8859-1 -->
  <property name="defaultEncoding" value="utf-8"/>
  <!-- 上傳文件大小上限,單位為字節(jié)(10485760=10M) -->
  <property name="maxUploadSize" value="10485760"/>
  <property name="maxInMemorySize" value="40960"/>
</bean>

CommonsMultipartFile 的 常用方法:

  • String getOriginalFilename():獲取上傳文件的原名

  • InputStream getInputStream():獲取文件流

  • void transferTo(File dest):將上傳文件保存到一個(gè)目錄文件中

我們?nèi)?shí)際測試一下

3、編寫前端頁面

<form action="/upload" enctype="multipart/form-data" method="post">
 <input type="file" name="file"/>
 <input type="submit" value="upload">
</form>

4、Controller

package com.xiaohua.controller;

import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.multipart.commons.CommonsMultipartFile;

import javax.servlet.http.HttpServletRequest;
import java.io.*;

@Controller
public class FileController {
  //@RequestParam("file") 將name=file控件得到的文件封裝成CommonsMultipartFile 對象
  //批量上傳CommonsMultipartFile則為數(shù)組即可
  @RequestMapping("/upload")
  public String fileUpload(@RequestParam("file") CommonsMultipartFile file , HttpServletRequest request) throws IOException {

    //獲取文件名 : file.getOriginalFilename();
    String uploadFileName = file.getOriginalFilename();

    //如果文件名為空,直接回到首頁!
    if ("".equals(uploadFileName)){
      return "redirect:/index.jsp";
    }
    System.out.println("上傳文件名 : "+uploadFileName);

    //上傳路徑保存設(shè)置
    String path = request.getServletContext().getRealPath("/upload");
    //如果路徑不存在,創(chuàng)建一個(gè)
    File realPath = new File(path);
    if (!realPath.exists()){
      realPath.mkdir();
    }
    System.out.println("上傳文件保存地址:"+realPath);

    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 "redirect:/index.jsp";
  }
}

5、測試上傳文件,OK!

采用file.Transto來保存上傳的文件

編寫Controller

/*
 * 采用file.Transto 來保存上傳的文件
 */
@RequestMapping("/upload2")
public String fileUpload2(@RequestParam("file") CommonsMultipartFile file, HttpServletRequest request) throws IOException {

  //上傳路徑保存設(shè)置
  String path = request.getServletContext().getRealPath("/upload");
  File realPath = new File(path);
  if (!realPath.exists()){
    realPath.mkdir();
  }
  //上傳文件地址
  System.out.println("上傳文件保存地址:"+realPath);

  //通過CommonsMultipartFile的方法直接寫文件(注意這個(gè)時(shí)候)
  file.transferTo(new File(realPath +"/"+ file.getOriginalFilename()));

  return "redirect:/index.jsp";
}

前端表單提交地址修改

訪問提交測試

文件下載
文件下載步驟:

  • 設(shè)置 response 響應(yīng)頭

  • 讀取文件 -- InputStream

  • 寫出文件 -- OutputStream

  • 執(zhí)行操作

  • 關(guān)閉流 (先開后關(guān))

代碼實(shí)現(xiàn):

@RequestMapping(value="/download")
public String downloads(HttpServletResponse response ,HttpServletRequest request) throws Exception{
  //要下載的圖片地址
  String path = request.getServletContext().getRealPath("/upload");
  String fileName = "基礎(chǔ)語法.jpg";

  //1、設(shè)置response 響應(yīng)頭
  response.reset(); //設(shè)置頁面不緩存,清空buffer
  response.setCharacterEncoding("UTF-8"); //字符編碼
  response.setContentType("multipart/form-data"); //二進(jìn)制傳輸數(shù)據(jù)
  //設(shè)置響應(yīng)頭
  response.setHeader("Content-Disposition",
      "attachment;fileName="+URLEncoder.encode(fileName, "UTF-8"));

  File file = new File(path,fileName);
  //2、 讀取文件--輸入流
  InputStream input=new FileInputStream(file);
  //3、 寫出文件--輸出流
  OutputStream out = response.getOutputStream();

  byte[] buff =new byte[1024];
  int index=0;
  //4、執(zhí)行 寫出操作
  while((index= input.read(buff))!= -1){
    out.write(buff, 0, index);
    out.flush();
  }
  out.close();
  input.close();
  return null;
}

前端

<a href="/download" rel="external nofollow" >點(diǎn)擊下載</a>

關(guān)于Spring mvc中怎么實(shí)現(xiàn)文件上傳下載功能就分享到這里了,希望以上內(nèi)容可以對大家有一定的幫助,可以學(xué)到更多知識。如果覺得文章不錯(cuò),可以把它分享出去讓更多的人看到。

向AI問一下細(xì)節(jié)

免責(zé)聲明:本站發(fā)布的內(nèi)容(圖片、視頻和文字)以原創(chuàng)、轉(zhuǎn)載和分享為主,文章觀點(diǎn)不代表本網(wǎng)站立場,如果涉及侵權(quán)請聯(lián)系站長郵箱:is@yisu.com進(jìn)行舉報(bào),并提供相關(guān)證據(jù),一經(jīng)查實(shí),將立刻刪除涉嫌侵權(quán)內(nèi)容。

AI