首頁 > 軟體

SpringBoot+BootStrap多檔案上傳到本地範例

2022-03-24 19:01:11

1、application.yml檔案設定

#  檔案大小 MB必須大寫
#  maxFileSize 是單個檔案大小
#  maxRequestSize是設定總上傳的資料大小
spring:
  servlet:
    multipart:
      enabled: true
      max-file-size: 20MB
      max-request-size: 20MB

2、application-resources.yml設定(自定義屬性)

#檔案上傳路徑
file:
  filepath: O:/QMDownload/Hotfix2/

3、後臺程式碼

(1)FileService.java

package com.sun123.springboot.service;
import org.springframework.web.multipart.MultipartFile;
import java.util.Map;
public interface FileService {
    Map<String,Object> fileUpload(MultipartFile[] file);
}

(2)FileServiceImpl.java

package com.sun123.springboot.service.impl;
import com.sun123.springboot.FileUtil;
import com.sun123.springboot.service.FileService;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Service;
import org.springframework.web.multipart.MultipartFile;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.File;
import java.io.FileInputStream;
import java.io.PrintWriter;
import java.util.*;
/**
 * @ClassName FileServiceImpl
 * @Description TODO
 * @Date 2019/3/22 22:19
 * @Version 1.0
 */
@Service
public class FileServiceImpl implements FileService {
    private static Logger log= LoggerFactory.getLogger(FileServiceImpl.class);
    //檔案上傳路徑    @Service包含@Component
    @Value("${file.filepath}")
    private String filepath;
    Map<String, Object> resultMap = new LinkedHashMap<String, Object>();
  //會將上傳資訊存入此處,根據需求自行調整
    List<String> fileName =new ArrayList<String>();
    //必須注入,不可以建立物件,否則組態檔參照的路徑屬性為null
    @Autowired
    FileUtil fileUtil;
    @Override
    public Map<String, Object> fileUpload(MultipartFile[] file) {
        HttpServletRequest request = null;
        HttpServletResponse response;
        resultMap.put("status", 400);
        if(file!=null&&file.length>0){
            //組合image名稱,「;隔開」
//            List<String> fileName =new ArrayList<String>();
            PrintWriter out = null;
            //圖片上傳
            try {
                for (int i = 0; i < file.length; i++) {
                    if (!file[i].isEmpty()) {
                        //上傳檔案,隨機名稱,","分號隔開
                        fileName.add(fileUtil.uploadImage(request, filepath+"upload/"+ fileUtil.formateString(new Date())+"/", file[i], true)+fileUtil.getOrigName());
                    }
                }
                //上傳成功
                if(fileName!=null&&fileName.size()>0){
                    System.out.println("上傳成功!");
                    resultMap.put("images",fileName);
                    resultMap.put("status", 200);
                    resultMap.put("message", "上傳成功!");
                }else {
                    resultMap.put("status", 500);
                    resultMap.put("message", "上傳失敗!檔案格式錯誤!");
                }
            } catch (Exception e) {
                e.printStackTrace();
                resultMap.put("status", 500);
                resultMap.put("message", "上傳異常!");
            }
            System.out.println("==========filename=========="+fileName);
        }else {
            resultMap.put("status", 500);
            resultMap.put("message", "沒有檢測到有效檔案!");
        }
        return resultMap;
    }
    }

(3)FileUtil.java

package com.sun123.springboot;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Component;
import org.springframework.web.multipart.MultipartFile;
import javax.servlet.http.HttpServletRequest;
import java.io.File;
import java.text.SimpleDateFormat;
import java.util.Date;
/**
 * Created by wangluming on 2018/5/24.
 */
@Component
public class FileUtil {
//    //檔案上傳路徑
//    @Value("${file.filepath}")
//    private String filepath;
    //檔案隨機名稱
    private String origName;
    public String getOrigName() {
        return origName;
    }
    public void setOrigName(String origName) {
        this.origName = origName;
    }
    /**
     *
     * @param request
     * @param path_deposit 新增目錄名 支援多級不存在目錄
     * @param file 待檔案
     * @param isRandomName 是否要基於圖片名稱重新編排名稱
     * @return
     */
    public String uploadImage(HttpServletRequest request, String path_deposit, MultipartFile file, boolean isRandomName) {
        //上傳
        try {
            String[] typeImg={"gif","png","jpg","docx","doc","pdf"};
            if(file!=null){
                origName=file.getOriginalFilename();// 檔案原名稱
                System.out.println("上傳的檔案原名稱:"+origName);
                // 判斷檔案型別
                String type=origName.indexOf(".")!=-1?origName.substring(origName.lastIndexOf(".")+1, origName.length()):null;
                if (type!=null) {
                    boolean booIsType=false;
                    for (int i = 0; i < typeImg.length; i++) {
                        if (typeImg[i].equals(type.toLowerCase())) {
                            booIsType=true;
                        }
                    }
                    //型別正確
                    if (booIsType) {
                        //存放圖片檔案的路徑
                        //String path="O:\QMDownload\Hotfix\";
                        //String path=filepath;
                        //System.out.print("檔案上傳的路徑"+path);
                        //組合名稱
                        //String fileSrc = path+path_deposit;
                        String fileSrc = path_deposit;
                        //是否隨機名稱
                        if(isRandomName){
                            //隨機名規則:檔名+_CY+當前日期+8位元亂數+檔案字尾名
                            origName=origName.substring(0,origName.lastIndexOf("."))+"_CY"+formateString(new Date())+
                                    MathUtil.getRandom620(8)+origName.substring(origName.lastIndexOf("."));
                        }
                        System.out.println("隨機檔名:"+origName);
                        //判斷是否存在目錄
                        File targetFile=new File(fileSrc,origName);
                        if(!targetFile.exists()){
                            targetFile.getParentFile().mkdirs();//建立目錄
                        }
                        //上傳
                        file.transferTo(targetFile);
                        //完整路徑
                        System.out.println("完整路徑:"+targetFile.getAbsolutePath());
                        return fileSrc;
                    }
                }
            }
            return null;
        }catch (Exception e) {
            e.printStackTrace();
            return null;
        }
    }
    /**
     * 格式化日期並去掉」-「
     * @param date
     * @return
     */
    public String formateString(Date date){
        SimpleDateFormat dateFormater = new SimpleDateFormat("yyyy-MM-dd");
        String list[] = dateFormater.format(date).split("-");
        String result = "";
        for (int i=0;i<list.length;i++) {
            result += list[i];
        }
        return result;
    }
}

(4)MathUtil.java

package com.sun123.springboot;
import java.security.MessageDigest;
import java.util.Random;
public class MathUtil {
    /**
     * 獲取隨機的數值。
     * @param length    長度
     * @return
     */
    public static String getRandom620(Integer length){
        String result = "";
        Random rand = new Random();
        int n = 20;
        if(null != length && length > 0){
            n = length;
        }
        boolean[]  bool = new boolean[n];
        int randInt = 0;
        for(int i = 0; i < length ; i++) {
            do {
                randInt  = rand.nextInt(n);
            }while(bool[randInt]);
            bool[randInt] = true;
            result += randInt;
        }
        return result;
    }
    /**
     * MD5 加密
     * @param str
     * @return
     * @throws Exception
     */
    public static String  getMD5(String str) {
        MessageDigest messageDigest = null;
        try {
            messageDigest = MessageDigest.getInstance("MD5");
            messageDigest.reset();
            messageDigest.update(str.getBytes("UTF-8"));
        } catch (Exception e) {
            //LoggerUtils.fmtError(MathUtil.class,e, "MD5轉換異常!message:%s", e.getMessage());
        }
        byte[] byteArray = messageDigest.digest();
        StringBuffer md5StrBuff = new StringBuffer();
        for (int i = 0; i < byteArray.length; i++) {
            if (Integer.toHexString(0xFF & byteArray[i]).length() == 1)
                md5StrBuff.append("0").append(Integer.toHexString(0xFF & byteArray[i]));
            else
                md5StrBuff.append(Integer.toHexString(0xFF & byteArray[i]));
        }
        return md5StrBuff.toString();
    }
}

(5)FileController.java

package com.sun123.springboot.controller;
import com.sun123.springboot.service.FileService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.multipart.MultipartFile;
import java.util.Map;
/**
 * @ClassName FileController
 * @Description TODO
 * @Date 2019/3/22 22:21
 * @Version 1.0
 */
@Controller
@RequestMapping(value = "/upload")
public class FileController {
    @Autowired
    private FileService fileService;
    @RequestMapping(value = "/UpLoadImage")
    @ResponseBody
    public Map<String,Object> fileUpload(@RequestParam("file") MultipartFile[] file) throws Exception {
        Map<String, Object> fileUpload = fileService.fileUpload(file);
        return fileUpload;
    }
}

4、前臺程式碼(bootstrap)

<div class="container" th:fragment="fileupload">
        <input id="uploadfile" type="file" class="file" multiple="multiple" name="file"/>
    </div>
<script>
    $("#uploadfile").fileinput({
        language: 'zh', //設定語言
        //uploadUrl: "http://127.0.0.1/testDemo/fileupload/upload.do", //上傳的地址
        uploadUrl: "/upload/UpLoadImage", //上傳的地址
        allowedFileExtensions: ['jpg', 'gif', 'png', 'docx', 'zip', 'txt'], //接收的檔案字尾
        //uploadExtraData:{"id": 1, "fileName":'123.mp3'},
        showClose: false,//是否顯示關閉按鈕
        uploadAsync: true, //預設非同步上傳
        showUpload: true, //是否顯示上傳按鈕
        //showBrowse: true, //是否顯示瀏覽按鈕
        showRemove: true, //顯示移除按鈕
        showPreview: true, //是否顯示預覽
        showCaption: false, //是否顯示標題
        browseClass: "btn btn-primary", //按鈕樣式
        dropZoneEnabled: true, //是否顯示拖拽區域
        //previewFileType: ['docx'], //預覽檔案型別
        //minImageWidth: 50, //圖片的最小寬度
        //minImageHeight: 50,//圖片的最小高度
        //maxImageWidth: 1000,//圖片的最大寬度
        //maxImageHeight: 1000,//圖片的最大高度
        maxFileSize:0,//單位為kb,如果為0表示不限制檔案大小
        //minFileCount: 0,
        maxFileCount: 10, //表示允許同時上傳的最大檔案個數
        enctype: 'multipart/form-data',
        validateInitialCount: true,
        previewFileIcon: "<iclass='glyphicon glyphicon-king'></i>",
        msgFilesTooMany: "選擇上傳的檔案數量({n}) 超過允許的最大數值{m}!",
    }).on("fileuploaded", function (event, data, previewId, index) {
    });
</script>

以上為個人經驗,希望能給大家一個參考,也希望大家多多支援it145.com。


IT145.com E-mail:sddin#qq.com