SpringMVC-文件下載與上傳

SpringMVC-文件下載與上傳

1.文件下載

2.文件上傳

1).導入相關jar包

2).在springmvc.xml配置文件中裝配MultpartResovler

 <!--上傳文件配置-->
    <bean id="multipartResolver" class="org.springframework.web.multipart.commons.CommonsMultipartResolver">
        <!--設置字符集的編碼-->
        <property name="defaultEncoding" value="UTF-8"/>
        <!--最大文件上傳尺寸-->
        <property name="maxUploadSize" value="102400"/>
    </bean>

代碼示例:

前端請求界面:

<%--文件下載--%>
  <a href="${pageContext.request.contextPath}/download/1.png">下載1.png</a>
  <a href="${pageContext.request.contextPath}/download/圖片.png">下載 圖片.png</a>


  <%--文件上傳--%>
  <hr>
  <form action="${pageContext.request.contextPath}/upload" method="post" enctype="multipart/form-data">
    <input type="file" name="file"><br>
    <input type="submit" value="上傳">
  </form>

後臺前端控制界面:

package com.helong.web.controller;

import org.springframework.http.HttpHeaders;
import org.springframework.http.HttpStatus;
import org.springframework.http.ResponseEntity;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.multipart.commons.CommonsMultipartFile;
import org.springframework.web.multipart.commons.CommonsMultipartResolver;

import javax.servlet.ServletContext;
import javax.servlet.http.HttpSession;
import java.io.*;
import java.net.URLEncoder;
import java.util.Map;

@Controller
public class MyController {
    //使用下面這種方式的時候就可以獲取文件的後綴名了
    @RequestMapping("/download/{filename:.+}")
    public ResponseEntity download(@PathVariable String filename, HttpSession httpSession) throws Exception {
        System.out.println(filename);

        //1.獲取文件的路徑
        ServletContext servletContext = httpSession.getServletContext();
        String realPath = servletContext.getRealPath("/download/" + filename);

        //2.把文件讀到程序裏面
        InputStream io = new FileInputStream(realPath);
        byte[] body = new byte[io.available()];
        io.read(body);

        //3.創建響應頭
        HttpHeaders httpHeaders = new HttpHeaders();
        /*解決中文文件名下載時不能顯示文件名的問題*/
        filename = URLEncoder.encode(filename,"utf-8");

        /*告訴瀏覽器以輔件的形式進行下載*/
        httpHeaders.add("Content-Disposition","attachment;filename="+filename);

        ResponseEntity<byte[]> responseEntity = new ResponseEntity<>(body, httpHeaders, HttpStatus.OK);

        return responseEntity;
    }

    //文件上傳
    @RequestMapping("upload")
    public String upload(@RequestParam("file") CommonsMultipartFile file,HttpSession session) throws IOException {
        System.out.println(file.getContentType());/*文件類型*/
        System.out.println(file.getOriginalFilename());/*文件名稱*/
        System.out.println(file.getSize());/*獲取文件大小*/
        System.out.println(file.getName());/*獲取文件對應的屬性名稱*/

        //確定文件上傳的路徑
        ServletContext servletContext = session.getServletContext();
        String realPath = servletContext.getRealPath("/upload");
        //變成程序當中的路徑
        File uploadPath = new File(realPath);
        if(!uploadPath.exists()){
            //如果路徑不存在,創建一個新文件夾
            uploadPath.mkdirs();
        }

        //確認最終的路徑   /文件夾/文件名       工程的名稱/upload/java.png
        String filename = file.getOriginalFilename();
        //將原來的路徑重新複製
        uploadPath = new File(uploadPath + "/" + filename);

        //開始上傳
        file.transferTo(uploadPath);

        return "result.jsp";
    }


}

3.多文件上傳(使用WebUploader由百度提供)

1).將文件引入對應位置

2).在springmvc.xml文件中設置允許靜態文件訪問

<!--開啓靜態文件訪問權限-->
<mvc:resources mapping="/js/**" location="/js/"/>
<mvc:resources mapping="/css/**" location="/css/"/>

3).前端的上傳界面示例:

<%@ page contentType="text/html;charset=UTF-8" language="java" %>
<html>
<head>
    <title>WebUploader文件上傳簡單示例</title>
    <%--引入css樣式--%>
    <link href="${pageContext.request.contextPath}/css/webuploader.css" rel="stylesheet" type="text/css"/>
    <script src="${pageContext.request.contextPath}/js/jquery-3.4.1.js" type="text/javascript"></script>
    <%--引入文件上傳插件--%>
    <script type="text/javascript" src="${pageContext.request.contextPath}/js/webuploader.js"></script>
    <script type="text/javascript">
        $(function () {
            var $ = jQuery,
                $list = $('#fileList'),
                //優化retina, 在retina下這個值是2
                ratio = window.devicePixelRatio || 1,
                // 縮略圖大小
                thumbnailWidth = 100 * ratio,
                thumbnailHeight = 100 * ratio,
                // Web Uploader實例uploader;
                // 初始化Web Uploader
                uploader = WebUploader.create({
                    // 自動上傳。
                    auto: false,
                    // swf文件路徑
                    swf: '${pageContext.request.contextPath}/js/Uploader.swf',
                    // 文件接收服務端。
                    server: '${pageContext.request.contextPath}/upload',
                    fileVal: 'file',
                    threads: '30',      //同時運行30個線程傳輸
                    fileNumLimit: '10',   //文件總數量只能選擇10個 
                    // 選擇文件的按鈕。可選。
                    pick: {
                        id: '#filePicker',  //選擇文件的按鈕
                        multiple: true        //允許可以同時選擇多個圖片
                    },
                    //圖片質量,只有type爲`image/jpeg`的時候纔有效。
                    quality: 100,
                    //限制傳輸文件類型,accept可以不寫 (用於顯示文件類型篩選)
                    /* accept: {
                    title: 'Images',//描述
                    extensions: 'gif,jpg,jpeg,bmp,png,zip',//類型
                    mimeTypes: 'image/*'//mime類型
                   } */
                });

            // 當有文件添加進來的時候,創建img顯示縮略圖使用
            uploader.on('fileQueued', function (file) {
                var $li = $(
                    '<div id="' + file.id + '" class="file-item thumbnail">' +
                    '<img>' +
                    '<div class="info">' + file.name + '</div>' +
                    '</div>'
                    ),
                    $img = $li.find('img');
                // $list爲容器jQuery實例
                $list.append($li);
                // 創建縮略圖
                // 如果爲非圖片文件,可以不用調用此方法。
                // thumbnailWidth x thumbnailHeight 爲 100 x 100
                uploader.makeThumb(file, function (error, src) {
                    if (error) {
                        $img.replaceWith('<span>不能預覽</span>');
                        return;
                    }
                    $img.attr('src', src);
                }, thumbnailWidth, thumbnailHeight);
            });
            // 文件上傳過程中創建進度條實時顯示。   
            // uploadProgress事件:上傳過程中觸發,攜帶上傳進度。
            // file文件對象 percentage傳輸進度 Number類型
            uploader.on('uploadProgress', function (file, percentage) {
                console.log(percentage);
            });
            // 文件上傳成功時候觸發,給item添加成功class,
            // 用樣式標記上傳成功。
            // file:文件對象,   
            // response:服務器返回數據
            uploader.on('uploadSuccess', function (file, response) {
                $('#' + file.id).addClass('upload-state-done');
                //console.info(response);
                $("#upInfo").html("<font color='red'>" + response._raw + "</font>");
            });
            // 文件上傳失敗
            // file:文件對象 ,
            // code:出錯代碼
            uploader.on('uploadError', function (file, code) {
                var $li = $('#' + file.id),
                    $error = $li.find('div.error');

                // 避免重複創建
                if (!$error.length) {
                    $error = $('<div class="error"></div>').appendTo($li);
                }
                $error.text('上傳失敗!');
            });

            // 不管成功或者失敗,
            // 文件上傳完成時觸發。
            // file: 文件對象
            uploader.on('uploadComplete', function (file) {
                $('#' + file.id).find('.progress').remove();
            });
            //綁定提交事件
            $("#btn").click(function () {
                console.log("上傳...");
                uploader.upload();   //執行手動提交
                console.log("上傳成功");
            });
        });
    </script>
    <script>
        var contextpath = ${pageContext.request.contextPath};
    </script>
    <script type="text/javascript" src=""></script>

</head>
<body style="padding:10px">
<h3>多文件上傳</h3>
    <!--dom結構部分-->
<div id="uploader-demo">
     <!--用來存放item-->
    <div id="fileList" class="uploader-list"></div>
    <div id="upInfo"></div>
    <div id="filePicker">選擇文件</div>
</div>
<input type="button" id="btn" value="開始上傳">

</body>
</html>

4).後臺前端控制器的設置與單文件上傳一致

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章