溫馨提示×

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

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

SpringBoot+BootStrap多文件上傳到本地的方法

發(fā)布時(shí)間:2022-03-25 09:13:40 來(lái)源:億速云 閱讀:149 作者:iii 欄目:開(kāi)發(fā)技術(shù)

這篇文章主要介紹“SpringBoot+BootStrap多文件上傳到本地的方法”的相關(guān)知識(shí),小編通過(guò)實(shí)際案例向大家展示操作過(guò)程,操作方法簡(jiǎn)單快捷,實(shí)用性強(qiáng),希望這篇“SpringBoot+BootStrap多文件上傳到本地的方法”文章能幫助大家解決問(wèn)題。

    1、application.yml文件配置

    #  文件大小 MB必須大寫
    #  maxFileSize 是單個(gè)文件大小
    #  maxRequestSize是設(shè)置總上傳的數(shù)據(jù)大小
    spring:
      servlet:
        multipart:
          enabled: true
          max-file-size: 20MB
          max-request-size: 20MB

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

    #文件上傳路徑
    file:
      filepath: O:/QMDownload/Hotfix2/

    3、后臺(tái)代碼

    (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>();
      //會(huì)將上傳信息存入此處,根據(jù)需求自行調(diào)整
        List<String> fileName =new ArrayList<String>();
        //必須注入,不可以創(chuàng)建對(duì)象,否則配置文件引用的路徑屬性為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名稱,“;隔開(kāi)”
    //            List<String> fileName =new ArrayList<String>();
                PrintWriter out = null;
                //圖片上傳
                try {
                    for (int i = 0; i < file.length; i++) {
                        if (!file[i].isEmpty()) {
                            //上傳文件,隨機(jī)名稱,","分號(hào)隔開(kāi)
                            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", "上傳失?。∥募袷藉e(cuò)誤!");
                    }
                } 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", "沒(méi)有檢測(cè)到有效文件!");
            }
            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;
        //文件隨機(jī)名稱
        private String origName;
        public String getOrigName() {
            return origName;
        }
        public void setOrigName(String origName) {
            this.origName = origName;
        }
        /**
         *
         * @param request
         * @param path_deposit 新增目錄名 支持多級(jí)不存在目錄
         * @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;
                            //是否隨機(jī)名稱
                            if(isRandomName){
                                //隨機(jī)名規(guī)則:文件名+_CY+當(dāng)前日期+8位隨機(jī)數(shù)+文件后綴名
                                origName=origName.substring(0,origName.lastIndexOf("."))+"_CY"+formateString(new Date())+
                                        MathUtil.getRandom620(8)+origName.substring(origName.lastIndexOf("."));
                            }
                            System.out.println("隨機(jī)文件名:"+origName);
                            //判斷是否存在目錄
                            File targetFile=new File(fileSrc,origName);
                            if(!targetFile.exists()){
                                targetFile.getParentFile().mkdirs();//創(chuàng)建目錄
                            }
                            //上傳
                            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 {
        /**
         * 獲取隨機(jī)的數(shù)值。
         * @param length    長(zhǎng)度
         * @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轉(zhuǎn)換異常!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、前臺(tái)代碼(bootstrap)

    <div class="container" th:fragment="fileupload">
            <input id="uploadfile" type="file" class="file" multiple="multiple" name="file"/>
        </div>
    <script>
        $("#uploadfile").fileinput({
            language: 'zh', //設(shè)置語(yǔ)言
            //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,//是否顯示關(guān)閉按鈕
            uploadAsync: true, //默認(rèn)異步上傳
            showUpload: true, //是否顯示上傳按鈕
            //showBrowse: true, //是否顯示瀏覽按鈕
            showRemove: true, //顯示移除按鈕
            showPreview: true, //是否顯示預(yù)覽
            showCaption: false, //是否顯示標(biāo)題
            browseClass: "btn btn-primary", //按鈕樣式
            dropZoneEnabled: true, //是否顯示拖拽區(qū)域
            //previewFileType: ['docx'], //預(yù)覽文件類型
            //minImageWidth: 50, //圖片的最小寬度
            //minImageHeight: 50,//圖片的最小高度
            //maxImageWidth: 1000,//圖片的最大寬度
            //maxImageHeight: 1000,//圖片的最大高度
            maxFileSize:0,//單位為kb,如果為0表示不限制文件大小
            //minFileCount: 0,
            maxFileCount: 10, //表示允許同時(shí)上傳的最大文件個(gè)數(shù)
            enctype: 'multipart/form-data',
            validateInitialCount: true,
            previewFileIcon: "<iclass='glyphicon glyphicon-king'></i>",
            msgFilesTooMany: "選擇上傳的文件數(shù)量({n}) 超過(guò)允許的最大數(shù)值{m}!",
        }).on("fileuploaded", function (event, data, previewId, index) {
        });
    </script>

    關(guān)于“SpringBoot+BootStrap多文件上傳到本地的方法”的內(nèi)容就介紹到這里了,感謝大家的閱讀。如果想了解更多行業(yè)相關(guān)的知識(shí),可以關(guān)注億速云行業(yè)資訊頻道,小編每天都會(huì)為大家更新不同的知識(shí)點(diǎn)。

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

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

    AI