SpringBoot+BootStrap多文件上傳到本地實(shí)例
更新時(shí)間:2022年03月24日 16:32:02 作者:清晨的第一抹陽光
這篇文章主要介紹了SpringBoot+BootStrap多文件上傳到本地實(shí)例,具有很好的參考價(jià)值,希望對(duì)大家有所幫助。如有錯(cuò)誤或未考慮完全的地方,望不吝賜教
1、application.yml文件配置
# 文件大小 MB必須大寫
# maxFileSize 是單個(gè)文件大小
# maxRequestSize是設(shè)置總上傳的數(shù)據(jù)大小
spring:
servlet:
multipart:
enabled: true
max-file-size: 20MB
max-request-size: 20MB2、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名稱,“;隔開”
// 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)隔開
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", "沒有檢測(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 長度
* @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è)置語言
//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}) 超過允許的最大數(shù)值{m}!",
}).on("fileuploaded", function (event, data, previewId, index) {
});
</script>以上為個(gè)人經(jīng)驗(yàn),希望能給大家一個(gè)參考,也希望大家多多支持腳本之家。
相關(guān)文章
Java中如何動(dòng)態(tài)創(chuàng)建接口的實(shí)現(xiàn)方法
這篇文章主要介紹了Java中如何動(dòng)態(tài)創(chuàng)建接口的實(shí)現(xiàn)方法的相關(guān)資料,需要的朋友可以參考下2017-09-09
自定義Jackson的ObjectMapper如何實(shí)現(xiàn)@ResponseBody的自定義渲染
這篇文章主要介紹了自定義Jackson的ObjectMapper如何實(shí)現(xiàn)@ResponseBody的自定義渲染,具有很好的參考價(jià)值,希望對(duì)大家有所幫助,如有錯(cuò)誤或未考慮完全的地方,望不吝賜教2024-07-07
利用Netty+SpringBoot實(shí)現(xiàn)定時(shí)后端向前端推送數(shù)據(jù)
這篇文章主要介紹了BIO、NIO、AIO三種Java?IO模型,并探討了如何使用Spring?Boot集成Netty實(shí)現(xiàn)后臺(tái)向前端推送信息的功能,文中通過代碼介紹的非常詳細(xì),需要的朋友可以參考下2025-01-01
Java高性能實(shí)體類轉(zhuǎn)換工具M(jìn)apStruct的使用教程詳解
MapStruct 是一個(gè)代碼生成器,它基于約定優(yōu)于配置的方法,極大地簡化了 Java bean 類型之間的映射實(shí)現(xiàn),本文主要介紹了MapStruct的具體使用以及如何進(jìn)行實(shí)體類轉(zhuǎn)換,感興趣的可以了解下2024-03-03
java實(shí)現(xiàn)斗地主發(fā)牌系統(tǒng)
這篇文章主要為大家詳細(xì)介紹了java實(shí)現(xiàn)斗地主發(fā)牌系統(tǒng),文中示例代碼介紹的非常詳細(xì),具有一定的參考價(jià)值,感興趣的小伙伴們可以參考一下2020-04-04
ReentrantLock從源碼解析Java多線程同步學(xué)習(xí)
這篇文章主要為大家介紹了ReentrantLock從源碼解析Java多線程同步學(xué)習(xí),有需要的朋友可以借鑒參考下,希望能夠有所幫助,祝大家多多進(jìn)步,早日升職加薪2023-04-04

