SpringBoot+BootStrap多文件上传到本地实例

网友投稿 1043 2022-10-17

SpringBoot+BootStrap多文件上传到本地实例

SpringBoot+BootStrap多文件上传到本地实例

目录1、application.yml文件配置2、application-resources.yml配置(自定义属性)3、后台代码(1)FileService.java(2)FileServiceImpl.java(3)FileUtil.java(4)MathUtil.java(5)FileController.java4、前台代码(bootstrap)

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 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 resultMap = new LinkedHashMap();

  //会将上传信息存入此处,根据需求自行调整

List fileName =new ArrayList();

//必须注入,不可以创建对象,否则配置文件引用的路径属性为null

@Autowired

FileUtil fileUtil;

@Override

public Map fileUpload(MultipartFile[] file) {

HttpServletRequest request = null;

HttpServletResponse response;

resultMap.put("status", 400);

if(file!=null&&file.length>0){

//组合image名称,“;隔开”

// List fileName =new ArrayList();

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();// 文件原名称

DcmqibvLr 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(thttp://ype.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,orDcmqibvLrigName.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

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 fileUpload(@RequestParam("file") MultipartFile[] file) throws Exception {

Map fileUpload = fileService.fileUpload(file);

return fileUpload;

}

}

4、前台代码(bootstrap)

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 fileUpload(@RequestParam("file") MultipartFile[] file) throws Exception {

Map fileUpload = fileService.fileUpload(file);

return fileUpload;

}

}

4、前台代码(bootstrap)

版权声明:本文内容由网络用户投稿,版权归原作者所有,本站不拥有其著作权,亦不承担相应法律责任。如果您发现本站中有涉嫌抄袭或描述失实的内容,请联系我们jiasou666@gmail.com 处理,核实后本网站将在24小时内删除侵权内容。

上一篇:#yyds干货盘点# leetcode算法题:排序链表
下一篇:Luy,一个类React框架
相关文章

 发表评论

暂时没有评论,来抢沙发吧~