最新国产好看的视频,伊人天堂AV在线,国产Aaaaaa视频,蜜臀视频在线观看一区,人妻av色图,密臀久久久精品影片,青青视频免费观看毛片,久草在线观看视,国产三级精品色情在线

SpringMVC實(shí)現(xiàn)文件上傳與下載

 更新時(shí)間:2021年05月18日 12:02:08   作者:客官不愛喝酒  
這篇文章主要為大家詳細(xì)介紹了SpringMVC實(shí)現(xiàn)文件上傳與下載,文中示例代碼介紹的非常詳細(xì),具有一定的參考價(jià)值,感興趣的小伙伴們可以參考一下

本文實(shí)例為大家分享了SpringMVC實(shí)現(xiàn)文件上傳與下載的具體代碼,供大家參考,具體內(nèi)容如下

0.環(huán)境準(zhǔn)備

1.maven依賴

<dependencies>
    <dependency>
      <groupId>org.junit.jupiter</groupId>
      <artifactId>junit-jupiter-api</artifactId>
      <version>5.7.0</version>
      <scope>test</scope>
    </dependency>


    <!-- servlet依賴 -->
    <dependency>
      <groupId>javax.servlet</groupId>
      <artifactId>javax.servlet-api</artifactId>
      <version>3.1.0</version>
      <scope>provided</scope>
    </dependency>

    <!-- springMVC依賴 -->
    <dependency>
      <groupId>org.springframework</groupId>
      <artifactId>spring-webmvc</artifactId>
      <version>5.2.6.RELEASE</version>
    </dependency>

    <!-- 文件上傳的jar包 -->
    <dependency>
      <groupId>commons-io</groupId>
      <artifactId>commons-io</artifactId>
      <version>2.8.0</version>
    </dependency>
    <dependency>
      <groupId>commons-fileupload</groupId>
      <artifactId>commons-fileupload</artifactId>
      <version>1.3.3</version>
</dependency>

2.springConfig。xml配置文件

<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns="http://www.springframework.org/schema/beans"
       xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
       xmlns:context="http://www.springframework.org/schema/context"
       xmlns:mvc="http://www.springframework.org/schema/mvc"
       xsi:schemaLocation="http://www.springframework.org/schema/beans
       http://www.springframework.org/schema/beans/spring-beans.xsd
       http://www.springframework.org/schema/context
       https://www.springframework.org/schema/context/spring-context.xsd
       http://www.springframework.org/schema/mvc https://www.springframework.org/schema/mvc/spring-mvc.xsd">
    <!-- 開啟組件掃描   -->
    <context:component-scan base-package="com.compass.file"></context:component-scan>

    <!--聲明 配置springMVC視圖解析器-->
    <bean  class="org.springframework.web.servlet.view.InternalResourceViewResolver">
        <!--前綴:視圖文件的路徑-->
        <property name="prefix" value="/WEB-INF/view/" />
        <!--后綴:視圖文件的擴(kuò)展名-->
        <property name="suffix" value=".jsp" />
    </bean>

    <!--讀寫JSON的支持(Jackson)-->
    <mvc:annotation-driven />

<!--  配置多媒體解析  -->
    <bean id="multipartResolver" class="org.springframework.web.multipart.commons.CommonsMultipartResolver">
<!--  配置字符編碼集 -->
        <property name="defaultEncoding" value="utf-8"> </property>
<!-- 配置文件上傳大小 單位是字節(jié)    -1代表沒有限制 maxUploadSizePerFile是限制每個(gè)上傳文件的大小,而maxUploadSize是限制總的上傳文件大小  -->
        <property name="maxUploadSizePerFile" value="-1"> </property>

 <!-- ,不設(shè)置默認(rèn)不限制總的上傳文件大小,這里設(shè)置總的上傳文件大小不超過1M(1*1024*1024) -->
        <property name="maxUploadSize" value="1048576"/>

    </bean>

</beans>

3.web.xml配置

<?xml version="1.0" encoding="UTF-8"?>
<web-app xmlns="http://xmlns.jcp.org/xml/ns/javaee"
         xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
         xsi:schemaLocation="http://xmlns.jcp.org/xml/ns/javaee http://xmlns.jcp.org/xml/ns/javaee/web-app_4_0.xsd"
         version="4.0">
  <!-- 聲明springMvc的核心對(duì)象 DispatcherServlet -->
  <servlet>
    <servlet-name>web</servlet-name>
    <servlet-class>org.springframework.web.servlet.DispatcherServlet</servlet-class>
    <init-param>
      <param-name>contextConfigLocation</param-name>
      <param-value>classpath:springConfig.xml</param-value>
    </init-param>
    <load-on-startup>1</load-on-startup>
  </servlet>
  <servlet-mapping>
    <servlet-name>web</servlet-name>
    <url-pattern>*.mvc</url-pattern>
  </servlet-mapping>

  <!--  注冊(cè)字符集過濾器,解決post請(qǐng)求的中文亂碼問題-->
  <filter>
    <filter-name>characterEncodingFilter</filter-name>
    <filter-class>org.springframework.web.filter.CharacterEncodingFilter</filter-class>
    <init-param>
      <param-name>encoding</param-name>
      <param-value>utf-8</param-value>
    </init-param>
    <init-param>
      <param-name>forRequestEncoding</param-name>
      <param-value>true</param-value>
    </init-param>
    <init-param>
      <param-name>forResponseEncoding</param-name>
      <param-value>true</param-value>
    </init-param>

  </filter>
  <filter-mapping>
    <filter-name>characterEncodingFilter</filter-name>
    <url-pattern>/*</url-pattern>
  </filter-mapping>
</web-app>

1.文件上傳

文件上傳分為三種方式:

  • 單個(gè)文件單字段
  • 多個(gè)文件單字段
  • 多個(gè)文件多字段

注意點(diǎn):

1、提交方式為表單的post請(qǐng)求
2、from屬性中必須有enctype=“multipart/form-data”
3、如果是單字段多文件:輸入框中的屬性必須為:multiple=“multiple”
4、表單中的屬性name必須和后端參數(shù)一致

1.前端代碼

<%@ page contentType="text/html;charset=UTF-8" language="java" %>
<html>
<head>
    <title>文件上傳</title>
</head>
<body>

<div>
    <p style="text-align: center">文件上傳(單個(gè)文件單字段上傳)</p>
    <form action="${pageContext.request.contextPath}/uploadFile1.mvc" method="post"  enctype="multipart/form-data">
        <input type="file" name="file">
        <input type="submit" value="提交">
    </form>
</div>

<div>
    <p style="text-align: center">文件上傳(多文件單字段上傳)</p>
    <form action="${pageContext.request.contextPath}/uploadFile2.mvc" method="post"  enctype="multipart/form-data">
        <input type="file" name="file" multiple="multiple">
        <input type="submit" value="提交">
    </form>
</div>


<div>
    <p style="text-align: center">文件上傳(多文件多字段上傳)</p>
    <form action="${pageContext.request.contextPath}/uploadFile2.mvc" method="post"  enctype="multipart/form-data">
        <input type="file" name="file" >
        <input type="file" name="file" >
        <input type="submit" value="提交">
    </form>
</div>

</body>
</html>

2.后端代碼

import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.multipart.MultipartFile;
import org.springframework.web.servlet.ModelAndView;

import javax.servlet.http.HttpSession;
import java.io.File;
import java.io.IOException;

/**
 * @author compass
 * @version 1.0
 * @date 2021-05-11 14:33
 */
@Controller
public class UploadIFileController {

    // 處理單個(gè)文件上傳
    @PostMapping("/uploadFile1.mvc")
     public ModelAndView uploadFile1(MultipartFile file, HttpSession session) throws IOException {

        ModelAndView view = new ModelAndView();
        // 得到文件名稱
        String filename=file.getOriginalFilename();
        System.out.println("文件名稱:"+filename);
        if (!file.isEmpty()){
            // 判斷文件的后綴
            if (filename.endsWith(".jpg")||filename.endsWith(".png")||filename.endsWith(".txt"));
            //設(shè)置文件的保存路徑
            String savePath="C:\\Users\\14823\\IdeaProjects\\springMVC\\fileupload\\src\\main\\webapp\\WEB-INF\\file";
            File srcFile = new File(savePath,filename);
            // 執(zhí)行文件保存操作
            file.transferTo(srcFile);
            view.setViewName("forward:/uploadSuccess.jsp");
        }else {
            view.setViewName("forward:/uploadFailed.jsp");
        }
        return view;
    }

    // 處理多文件上傳
    @PostMapping("/uploadFile2.mvc")
    public ModelAndView uploadFile2(MultipartFile[] file,HttpSession session) throws IOException {

        ModelAndView view = new ModelAndView();
        //設(shè)置文件的保存路徑
        String savePath="C:\\Users\\14823\\IdeaProjects\\springMVC\\fileupload\\src\\main\\webapp\\WEB-INF\\file";
        String[] filenames = new String[file.length];
        // 只要上傳過來的文件為空或者是不符合指定類型的都會(huì)上傳失敗
        for (int i = 0; i <filenames.length ; i++) {
            // 判斷上傳過來的文件是否為空
            if (!file[i].isEmpty()){
               String filename=file[i].getOriginalFilename();
               // 判斷文件類型
               if (filename.endsWith(".txt")||filename.endsWith(".jpg")||filename.endsWith(".png")){
                   // 創(chuàng)建一個(gè)文件對(duì)象
                   File srcFile = new File(savePath, filename);
                   // 執(zhí)行保存文件操作
                   file[i].transferTo(srcFile);
                   view.setViewName("forward:/uploadSuccess.jsp");
               }else {
                   view.setViewName("forward:/uploadSuccess.jsp");
               }

            }else {
                view.setViewName("forward:/uploadFailed.jsp");
            }

        }
        return view;
    }
}

2.文件下載

文件下分為兩種情況:

  • 文件名稱是純英文字母的
  • 文件名帶有中文不處理會(huì)亂碼的

1.前端代碼

<%@ page contentType="text/html;charset=UTF-8" language="java" %>
<html>
<head>
    <title>文件下載</title>
</head>
<body>
<h1 style="text-align: center"><a href="${pageContext.request.contextPath}/download1.mvc?filename=preview.jpg" rel="external nofollow" >文件下載(非中文名稱)</a></h1>
<h1 style="text-align: center"><a href="${pageContext.request.contextPath}/download2.mvc?filename=文件下載.txt" rel="external nofollow" >文件下載(中文名稱)</a></h1>
</body>
</html>

2.后端代碼

/**
 * @author compass
 * @version 1.0
 * @date 2021-05-11 15:23
 */
@Controller
public class DownloadController {

    // 非中文名稱文件下載
    @GetMapping("/download1.mvc")
    public ResponseEntity <byte[]> fileDownload1(String filename,HttpServletRequest request) throws IOException {

        String path="C:\\Users\\14823\\IdeaProjects\\springMVC\\fileupload\\src\\main\\webapp\\WEB-INF\\file\\";
        File file = new File(path,filename);
        HttpHeaders header = new HttpHeaders();
        header.setContentDispositionFormData("attachment",filename);
        header.setContentType(MediaType.APPLICATION_OCTET_STREAM);
        ResponseEntity<byte[]> result = new ResponseEntity<>(FileUtils.readFileToByteArray(file), header, HttpStatus.OK);
        return result;
    }

    // 中文名稱文件下載
    @GetMapping("/download2.mvc")
    public ResponseEntity <byte[]> fileDownload2(String filename,HttpServletRequest request) throws IOException {

        System.out.println(filename);
        String path="C:\\Users\\14823\\IdeaProjects\\springMVC\\fileupload\\src\\main\\webapp\\WEB-INF\\file\\";
        filename = filename.replace("_", "%");
        filename= URLDecoder.decode(filename,"UTF-8");
        String downloadFile="";
        if (request.getHeader("USER-AGENT").toLowerCase().indexOf("msie")>0){
            filename= URLEncoder.encode(filename,"UTF-8");
            downloadFile=filename.replaceAll("+","%20");
        }else {
            downloadFile=new String(filename.getBytes("UTF-8"),"ISO-8859-1");
        }
        File file = new File(path,filename);
        HttpHeaders header = new HttpHeaders();
        header.setContentDispositionFormData("attachment",downloadFile);
        header.setContentType(MediaType.APPLICATION_OCTET_STREAM);
        ResponseEntity<byte[]> result = new ResponseEntity<>(FileUtils.readFileToByteArray(file), header, HttpStatus.OK);
        return result;
    }

}

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

相關(guān)文章

  • Java的System.getProperty()方法獲取大全

    Java的System.getProperty()方法獲取大全

    這篇文章主要介紹了Java的System.getProperty()方法獲取大全,羅列了System.getProperty()方法獲取各類信息的用法,具有一定的參考借鑒價(jià)值,需要的朋友可以參考下
    2014-12-12
  • IDEA導(dǎo)入eclipse項(xiàng)目并且部署到tomcat的步驟詳解

    IDEA導(dǎo)入eclipse項(xiàng)目并且部署到tomcat的步驟詳解

    這篇文章主要給大家介紹了關(guān)于IDEA導(dǎo)入eclipse項(xiàng)目并且部署到tomcat的相關(guān)資料,文中通過圖文介紹的非常詳細(xì),對(duì)大家的學(xué)習(xí)或者工作具有一定的參考學(xué)習(xí)價(jià)值,需要的朋友們下面來一起學(xué)習(xí)學(xué)習(xí)吧
    2019-02-02
  • Java?Dubbo服務(wù)調(diào)用擴(kuò)展點(diǎn)Filter使用教程

    Java?Dubbo服務(wù)調(diào)用擴(kuò)展點(diǎn)Filter使用教程

    Dubbo是阿里巴巴公司開源的一個(gè)高性能優(yōu)秀的服務(wù)框架,使得應(yīng)用可通過高性能的RPC實(shí)現(xiàn)服務(wù)的輸出和輸入功能,可以和Spring框架無縫集成
    2022-12-12
  • Docker?快速部署Springboot項(xiàng)目超詳細(xì)最新版

    Docker?快速部署Springboot項(xiàng)目超詳細(xì)最新版

    這篇文章主要介紹了Docker?快速部署Springboot項(xiàng)目超詳細(xì)最新版的相關(guān)資料,本文給大家介紹的非常詳細(xì),對(duì)大家的學(xué)習(xí)或工作具有一定的參考借鑒價(jià)值,需要的朋友可以參考下
    2021-04-04
  • java設(shè)計(jì)模式--七大原則詳解

    java設(shè)計(jì)模式--七大原則詳解

    本篇文章主要對(duì)Java中的設(shè)計(jì)模式如,創(chuàng)建型模式、結(jié)構(gòu)型模式和行為型模式以及7大原則進(jìn)行了歸納整理,需要的朋友可以參考下,希望能給你帶來幫助
    2021-07-07
  • 基于Java設(shè)計(jì)一個(gè)短鏈接生成系統(tǒng)

    基于Java設(shè)計(jì)一個(gè)短鏈接生成系統(tǒng)

    相信大家在生活中會(huì)收到很多短信,而這些短信都有一個(gè)特點(diǎn)是鏈接很短。這些鏈接背后的原理是什么呢?怎么實(shí)現(xiàn)的?小編今天就帶你們?cè)敿?xì)了解一下
    2021-12-12
  • 談?wù)勛兞棵?guī)范的重要性

    談?wù)勛兞棵?guī)范的重要性

    下面小編就為大家?guī)硪黄務(wù)勛兞棵?guī)范的重要性。小編覺得挺不錯(cuò)的,現(xiàn)在就分享給大家,也給大家做個(gè)參考。一起跟隨小編過來看看吧
    2017-01-01
  • SpringBoot如何使用feign實(shí)現(xiàn)遠(yuǎn)程接口調(diào)用和錯(cuò)誤熔斷

    SpringBoot如何使用feign實(shí)現(xiàn)遠(yuǎn)程接口調(diào)用和錯(cuò)誤熔斷

    這篇文章主要介紹了SpringBoot如何使用feign實(shí)現(xiàn)遠(yuǎn)程接口調(diào)用和錯(cuò)誤熔斷,文中通過示例代碼介紹的非常詳細(xì),對(duì)大家的學(xué)習(xí)或者工作具有一定的參考學(xué)習(xí)價(jià)值,需要的朋友可以參考下
    2019-12-12
  • springboot配置允許循環(huán)依賴問題

    springboot配置允許循環(huán)依賴問題

    這篇文章主要介紹了springboot配置允許循環(huán)依賴問題,具有很好的參考價(jià)值,希望對(duì)大家有所幫助。如有錯(cuò)誤或未考慮完全的地方,望不吝賜教
    2023-05-05
  • Java實(shí)現(xiàn)Word/Pdf/TXT轉(zhuǎn)html的示例

    Java實(shí)現(xiàn)Word/Pdf/TXT轉(zhuǎn)html的示例

    這篇文章主要介紹了Java實(shí)現(xiàn)Word/Pdf/TXT轉(zhuǎn)html的示例,幫助大家方便的進(jìn)行文件格式轉(zhuǎn)換,完成需求,感興趣的朋友可以了解下
    2020-11-11

最新評(píng)論

盐山县| 锦州市| 贵阳市| 西平县| 泉州市| 克东县| 新蔡县| 射洪县| 科技| 北流市| 海盐县| 德江县| 米易县| 石首市| 台中县| 阜阳市| 克拉玛依市| 九寨沟县| 孙吴县| 石阡县| 旬阳县| 偏关县| 肇源县| 且末县| 那曲县| 乌审旗| 乌兰浩特市| 梧州市| 新田县| 广州市| 河津市| 娄烦县| 台山市| 寻乌县| 德保县| 太原市| 芜湖县| 渭南市| 伊金霍洛旗| 兴业县| 安新县|