欧美bbbwbbbw肥妇,免费乱码人妻系列日韩,一级黄片

SpringBoot+BootStrap多文件上傳到本地實(shí)例

 更新時(shí)間:2022年03月24日 16:32:02   作者:清晨的第一抹陽(yáng)光  
這篇文章主要介紹了SpringBoot+BootStrap多文件上傳到本地實(shí)例,具有很好的參考價(jià)值,希望對(duì)大家有所幫助。如有錯(cuò)誤或未考慮完全的地方,望不吝賜教

1、application.yml文件配置

#  文件大小 MB必須大寫(xiě)
#  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名稱(chēng),“;隔開(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ī)名稱(chēng),","分號(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ī)名稱(chēng)
    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 是否要基于圖片名稱(chēng)重新編排名稱(chēng)
     * @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();// 文件原名稱(chēng)
                System.out.println("上傳的文件原名稱(chēng):"+origName);
                // 判斷文件類(lèi)型
                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;
                        }
                    }
                    //類(lèi)型正確
                    if (booIsType) {
                        //存放圖片文件的路徑
                        //String path="O:\\QMDownload\\Hotfix\\";
                        //String path=filepath;
                        //System.out.print("文件上傳的路徑"+path);
                        //組合名稱(chēng)
                        //String fileSrc = path+path_deposit;
                        String fileSrc = path_deposit;
                        //是否隨機(jī)名稱(chēng)
                        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ù)覽文件類(lèi)型
        //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>

以上為個(gè)人經(jīng)驗(yàn),希望能給大家一個(gè)參考,也希望大家多多支持腳本之家。

相關(guān)文章

  • Java中Comparable和Comparator兩種比較器的區(qū)別詳解

    Java中Comparable和Comparator兩種比較器的區(qū)別詳解

    這篇文章主要介紹了Java中Comparable和Comparator兩種比較器的區(qū)別詳解,Comparable接口將比較代碼嵌入自身類(lèi)中,像Integer、String等這些基本類(lèi)型的JAVA封裝類(lèi)都已經(jīng)實(shí)現(xiàn)了Comparable接口,這些類(lèi)對(duì)象本身就支持和自己比較,需要的朋友可以參考下
    2023-09-09
  • 自己寫(xiě)的java日志類(lèi)和方法代碼分享

    自己寫(xiě)的java日志類(lèi)和方法代碼分享

    這篇文章主要介紹了一個(gè)自己寫(xiě)的java日志類(lèi)和方法,下面把代碼分享給大家
    2014-01-01
  • java sqlserver text 類(lèi)型字段讀取方法

    java sqlserver text 類(lèi)型字段讀取方法

    有這樣一個(gè)需求,需要將原本存儲(chǔ)在數(shù)據(jù)庫(kù)中的文檔轉(zhuǎn)存至文件系統(tǒng)中,于是寫(xiě)了一個(gè)簡(jiǎn)單的程序完成此功能
    2012-11-11
  • java實(shí)現(xiàn)圖片的上傳與展示實(shí)例代碼

    java實(shí)現(xiàn)圖片的上傳與展示實(shí)例代碼

    這篇文章主要給大家介紹了關(guān)于java實(shí)現(xiàn)圖片的上傳與展示的相關(guān)資料,文中通過(guò)示例代碼介紹的非常詳細(xì),對(duì)大家的學(xué)習(xí)或者工作具有一定的參考學(xué)習(xí)價(jià)值,需要的朋友們下面隨著小編來(lái)一起學(xué)習(xí)學(xué)習(xí)吧
    2018-12-12
  • jvm細(xì)節(jié)探索之synchronized及實(shí)現(xiàn)問(wèn)題分析

    jvm細(xì)節(jié)探索之synchronized及實(shí)現(xiàn)問(wèn)題分析

    這篇文章主要介紹了jvm細(xì)節(jié)探索之synchronized及實(shí)現(xiàn)問(wèn)題分析,涉及synchronized的字節(jié)碼表示,JVM中鎖的優(yōu)化,對(duì)象頭的介紹等相關(guān)內(nèi)容,具有一定借鑒價(jià)值,需要的朋友可以參考下。
    2017-11-11
  • java數(shù)組算法例題代碼詳解(冒泡排序,選擇排序,找最大值、最小值,添加、刪除元素等)

    java數(shù)組算法例題代碼詳解(冒泡排序,選擇排序,找最大值、最小值,添加、刪除元素等)

    這篇文章主要介紹了java數(shù)組算法例題代碼詳解(冒泡排序,選擇排序,找最大值、最小值,添加、刪除元素等),本文給大家介紹的非常詳細(xì),對(duì)大家的學(xué)習(xí)或工作具有一定的參考借鑒價(jià)值,需要的朋友可以參考下
    2021-05-05
  • elasticsearch kibana簡(jiǎn)單查詢(xún)講解

    elasticsearch kibana簡(jiǎn)單查詢(xún)講解

    今天小編就為大家分享一篇關(guān)于elasticsearch kibana簡(jiǎn)單查詢(xún)講解,小編覺(jué)得內(nèi)容挺不錯(cuò)的,現(xiàn)在分享給大家,具有很好的參考價(jià)值,需要的朋友一起跟隨小編來(lái)看看吧
    2019-02-02
  • 淺析Java8新特性L(fǎng)ambda表達(dá)式和函數(shù)式接口

    淺析Java8新特性L(fǎng)ambda表達(dá)式和函數(shù)式接口

    Lambda表達(dá)式理解為是 一段可以傳遞的代碼。最直觀(guān)的是使用Lambda表達(dá)式之后不用再寫(xiě)大量的匿名內(nèi)部類(lèi),簡(jiǎn)化代碼,提高了代碼的可讀性
    2017-08-08
  • Java?easyexcel使用教程之導(dǎo)出篇

    Java?easyexcel使用教程之導(dǎo)出篇

    EasyExcel是阿里巴巴開(kāi)源的一個(gè)excel處理框架,以使用簡(jiǎn)單,節(jié)省內(nèi)存著稱(chēng),下面這篇文章主要給大家介紹了關(guān)于Java?easyexcel使用教程之導(dǎo)出篇的相關(guān)資料,文中通過(guò)實(shí)例代碼介紹的非常詳細(xì),需要的朋友可以參考下
    2022-06-06
  • java 流與 byte[] 的互轉(zhuǎn)操作

    java 流與 byte[] 的互轉(zhuǎn)操作

    這篇文章主要介紹了java 流與 byte[] 的互轉(zhuǎn)操作,具有很好的參考價(jià)值,希望對(duì)大家有所幫助。一起跟隨小編過(guò)來(lái)看看吧
    2020-10-10

最新評(píng)論