使用MultipartFile上传至本地或者文件服务器
直接上代码
一、前端上传至服务端(controller层)
package mon;import com.alibaba.fastjson.JSON;import com.app.base.basecontroller.BaseController;import com.mon.FileUploadEntity;import com.mon.FileUploadService;import com.mon;import mons.lang3.StringUtils;import org.slf4j.Logger;import org.slf4j.LoggerFactory;import org.springframework.beans.factory.annotation.Autowired;import org.springframework.web.bind.annotation.*;import org.springframework.web.multipart.MultipartFile;import java.util.ArrayList;import java.util.List;import java.util.Map;/*** 文件/图片上传公共接口** @Author Smily* @DateTime 2月3日*/@RequestMapping(value = "/fileUpload/")public class FileUploadController extends BaseController {public static Logger logger = LoggerFactory.getLogger(FileUploadController.class);@Autowiredprivate FileUploadService fileUploadService;/*** 文件/图片上传* @param files 文件集合* @param type 1储存相对路径 2储存绝对路径* @return* @Author Smily* @DateTime 7月14日*/@ResponseBody@RequestMapping(value = "uploadTest.html", method = RequestMethod.POST)public Object uploadTest(MultipartFile[] files,@RequestParam(defaultValue = "") String describe,//图片描述@RequestParam(defaultValue = "1") String type) //1返回图片相对路径 2返回图片绝对路径{if (files == null || (files.length == 1 && files[0].getSize() == 0)){return putData("图片为空");}Map<String, Object> map = fileUploadService.uploadTest(files,describe,type);return map;}}
二、service层
package com.mon;import com.mon.FileUploadEntity;import org.springframework.web.multipart.MultipartFile;import java.util.List;import java.util.Map;public interface FileUploadService {/*** 文件上传** @Param [files 文件, type 类型, describe 描述]* @Author: Smily* @Date: /2/3 14:00*/Map<String, Object> uploadTest(MultipartFile[] files,String describe, String type);}
三、文件上传实现类
将上传的文件分日期年月日进行储存,如果是图片就储存到图片目录,文件就储存到文件目录。
package com.mon.impl;import java.io.File;import java.text.SimpleDateFormat;import java.util.ArrayList;import java.util.Date;import java.util.List;import java.util.Map;import mons.lang3.StringUtils;import org.slf4j.Logger;import org.slf4j.LoggerFactory;import org.springframework.beans.factory.annotation.Value;import org.springframework.stereotype.Service;import org.springframework.web.multipart.MultipartFile;import com.app.base.basecontroller.BaseController;import com.mon.FileUploadService;import com.app.util.fileupload.ImageWatermarkUtil;/*** 文件/图片上传* @Author Smily* @DateTime 2月3日*/@Service("fileUploadService")public class FileUploadServiceImpl extends BaseController implements FileUploadService {public static Logger logger = LoggerFactory.getLogger(FileUploadServiceImpl.class);@Value("${httpHead}") //写自己的地址,或者文件服务器地址private String httpHead;@Overridepublic Map<String, Object> uploadTest(MultipartFile[] files, String describe, String type) {SimpleDateFormat sdf = new SimpleDateFormat("yyyyMMddHHmmssSSS");List<String> urlList = new ArrayList<>();for (int i = 0; i < files.length; i++) {MultipartFile file = files[i];String saveDBPath = "";if (file != null && file.getSize() > 0) {String fileName = file.getOriginalFilename();//根据文件类型储存在不同的文件夹下String extension = getSuffix(fileName);//文件格式if ((".pjpeg").equals(extension)) {//图片扩展名=转换extension = ".jpeg";}if (StringUtils.isBlank(extension)){logger.error("上传失败,未获取到文件名");return putData(Boolean.FALSE, "上传失败,未获取到文件名!", null);}//文件存储目录String datePath = new SimpleDateFormat("yyyy/MM/dd/").format(new Date());//根据日期创建不同目录String folderPath = "";if (isImage(extension)) {folderPath = "image/" + datePath;}else {folderPath = "file/" + datePath;}String path = "/home/file_storage/" + folderPath;//文件名 普通地址 命名方式:时间-数字-描述String newFileName = sdf.format(new Date()) + "-" + (i + 1) + extension;File targetFile = new File(path, newFileName);if (!targetFile.exists()) targetFile.mkdirs();try {file.transferTo(targetFile);//储存数据库文件名if ("1".equals(type)){//相对路径saveDBPath = "/fileserver/"+ folderPath + newFileName;}else if ("2".equals(type)){//绝对路径saveDBPath = httpHead + "/fileserver/"+ folderPath + newFileName;}urlList.add(saveDBPath);} catch (Exception e) {logger.error("文件上传失败", e);}}}return putData(Boolean.TRUE, "上传成功!", urlList);}/*** 获取文件后缀* @Author Smily* @DateTime 7月15日* @param filename* @return*/private String getSuffix(String filename) {if (StringUtils.isNotBlank(filename)){String suffix = "";int pos = filename.lastIndexOf('.');if (pos > 0 && pos < filename.length() - 1) {suffix = filename.substring(pos);}return suffix.toLowerCase();}return "";}/*** 判断文件类型* @param suffix* @Author Smily* @DateTime 7月15日* @return*/public static boolean isImage(String suffix) {suffix = suffix.toUpperCase();if (".PNG".equals(suffix)|| ".JPG".equals(suffix)|| ".JEPG".equals(suffix)|| ".JPEG".equals(suffix)|| ".BMP".equals(suffix)|| ".HEIC".equals(suffix)) {return true;}return false;}}
这里是我上传在本地的地址
第一篇文件上传就到这里,下一篇为上传的图片增加水印信息