Java做文件上传、图片上传后台方法
利用Springboot快速搭建项目环境
- 配置文件设置保存路径、上传文件大小限制。
#存放文件的根目录
my-file-path.root-path=E:/fileServer/uploadFile
#存放图片子目录
my-file-path.image-path=/img/
#存放文件子目录
my-file-path.file-path=/file/
#单个上传文件大小
spring.servlet.multipart.max-file-size=100MB
#总上传文件大小
spring.servlet.multipart.max-request-size=1000MB
- pom.xml 支持
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-web</artifactId>
</dependency>
<dependency>
<groupId>commons-fileupload</groupId>
<artifactId>commons-fileupload</artifactId>
<version>1.3.1</version>
</dependency>
- Base64工具类(图片Base64加密解密工具类)
- java后台代码
import com.bdxh.fileserver.utils.BaseController;
import com.bdxh.fileserver.utils.BaseResp;
import com.common.BASE64DecodedMultipartFile;
import com.common.DateUtil;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Controller;
import org.springframework.util.StringUtils;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.multipart.MultipartFile;
import org.springframework.web.multipart.MultipartHttpServletRequest;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.File;
import java.io.IOException;
import java.util.*;
@Controller
@RequestMapping("/uploadService/")
public class UploadServerController extends BaseController {
private static final Logger logger = LoggerFactory.getLogger(UploadServerController.class);
@Value("${my-file-path.root-path}")
private String rootPath;
@Value("${my-file-path.image-path}")
private String imagePath;
@Value("${my-file-path.file-path}")
private String filePath;
private HashMap<String, String> extMap = new HashMap<String, String>();
public UploadServerController() {
extMap.put("image", "gif,jpg,jpeg,png,bmp");
extMap.put("flash", "swf,flv");
extMap.put("media", "swf,flv,mp3,wav,wma,wmv,mid,avi,mpg,asf,rm,rmvb");
extMap.put("file", "doc,docx,xls,xlsx,ppt,pptx,htm,html,txt,zip,rar,gz,bz2");
}
@RequestMapping("uploadImg")
@ResponseBody
public BaseResp uploadImg(HttpServletRequest request, HttpServletResponse response){
try {
Map<String, Object> outMap = upload(request, initFilePath(imagePath), "image");
return BaseResp.success("上传成功",outMap);
}catch (IOException e){
e.printStackTrace();
return BaseResp.validError("上传文件出现异常:"+e.getMessage());
}catch (RuntimeException e){
e.printStackTrace();
return BaseResp.validError(e.getMessage());
}
}
@RequestMapping("uploadImgBase64")
@ResponseBody
public BaseResp uploadImgBase64(HttpServletRequest request, HttpServletResponse response){
Map<String,Object> outMap = new HashMap<>();
String imgBase64 = request.getParameter("base64Code");
if (StringUtils.isEmpty(imgBase64)){
return BaseResp.validError("未获取到上传图片内容");
}
MultipartFile file = BASE64DecodedMultipartFile.base64ToMultipart(imgBase64);
if (file == null) {
imgBase64 = "data:image/png;base64,"+imgBase64;
MultipartFile file2 = BASE64DecodedMultipartFile.base64ToMultipart(imgBase64);
if (file2 == null) {
return BaseResp.validError("图片base64格式转换失败。");
}else{
file = file2;
}
}
String filePath = initFilePath(imagePath);
String fileName = DateUtil.getFormatDate("yyyyMMddHHmmss", new Date()) + "_"
+ new Random().nextInt(1000);
String fileRealName = file.getOriginalFilename();
String[] str = fileRealName.split("\\.");
try {
File uploadedFile = new File(rootPath + filePath, fileName + "." + str[str.length - 1]);
file.transferTo(uploadedFile);
String imgUrl = filePath + fileName + "." + str[str.length - 1];
imgUrl = imgUrl.replaceAll("\\\\", "/").replaceAll("//", "/");
outMap.put("filePath",imgUrl);
outMap.put("fileName", fileRealName);
return BaseResp.success("上传成功",outMap);
} catch (Exception e) {
e.printStackTrace();
logger.error(e.getMessage());
return BaseResp.paramsError("上传文件失败。");
}
}
@RequestMapping("uploadifyImg")
@ResponseBody
public BaseResp uploadifyImg(HttpServletRequest request, HttpServletResponse response){
try {
List list = uploadify(request, initFilePath(imagePath), "image");
return BaseResp.success("上传成功",list);
}catch (IOException e){
e.printStackTrace();
return BaseResp.validError("上传文件出现异常:"+e.getMessage());
}catch (RuntimeException e){
e.printStackTrace();
return BaseResp.validError(e.getMessage());
}
}
@RequestMapping("uploadFile")
@ResponseBody
public BaseResp uploadFile(HttpServletRequest request, HttpServletResponse response){
try {
Map<String, Object> outMap = upload(request, initFilePath(filePath), null);
return BaseResp.success("上传成功",outMap);
}catch (IOException e){
e.printStackTrace();
return BaseResp.validError("上传文件出现异常:"+e.getMessage());
}catch (RuntimeException e){
e.printStackTrace();
return BaseResp.validError(e.getMessage());
}
}
@RequestMapping("uploadifyFile")
@ResponseBody
public BaseResp uploadifyFile(HttpServletRequest request, HttpServletResponse response){
try{
List list = uploadify(request,initFilePath(filePath),null);
return BaseResp.success("上传成功",list);
}catch (IOException e){
e.printStackTrace();
return BaseResp.validError("上传文件出现异常:"+e.getMessage());
}catch (RuntimeException e){
e.printStackTrace();
return BaseResp.validError(e.getMessage());
}
}
public Map<String,Object> upload(HttpServletRequest request,String filePath,String type)throws RuntimeException,IOException {
Map<String,Object> map = new HashMap<>();
MultipartHttpServletRequest multipartRequest = (MultipartHttpServletRequest) request;
Map<String, MultipartFile> fileMap = multipartRequest.getFileMap();
Iterator<String> it = fileMap.keySet().iterator();
while (it.hasNext()) {
String key = (String) it.next();
MultipartFile multipartFile = (MultipartFile) fileMap.get(key);
String fileName = DateUtil.getFormatDate("yyyyMMddHHmmss", new Date()) + "_"
+ new Random().nextInt(1000);
String fileRealName = multipartFile.getOriginalFilename();
String[] str = fileRealName.split("\\.");
if(!validateFileType(fileRealName,type)){
throw new RuntimeException("非法的文件类型.");
}
File uploadedFile = new File(rootPath + filePath, fileName + "." + str[str.length-1]);
multipartFile.transferTo(uploadedFile);
String imgUrl = filePath + fileName + "." + str[str.length - 1];
map.put("filePath", imgUrl);
map.put("fileName", fileRealName);
}
return map;
}
public List<Map<String,Object>> uploadify(HttpServletRequest request,String filePath,String type)throws IOException,RuntimeException{
List<Map<String,Object>> imagePathList = new ArrayList<>();
MultipartHttpServletRequest multipartRequest = (MultipartHttpServletRequest) request;
Map<String, MultipartFile> fileMap = multipartRequest.getFileMap();
Iterator<String> itValidate = fileMap.keySet().iterator();
Iterator<String> it = fileMap.keySet().iterator();
while (itValidate.hasNext()) {
String key = (String) itValidate.next();
MultipartFile multipartFile = (MultipartFile) fileMap.get(key);
String fileRealName = multipartFile.getOriginalFilename();
if(!validateFileType(fileRealName,type)){
throw new RuntimeException("非法的文件类型.");
}
}
while (it.hasNext()) {
String key = (String) it.next();
MultipartFile multipartFile = (MultipartFile) fileMap.get(key);
String fileName = DateUtil.getFormatDate("yyyyMMddHHmmss", new Date()) + "_"
+ new Random().nextInt(1000);
String fileRealName = multipartFile.getOriginalFilename();
String[] str = fileRealName.split("\\.");
File uploadedFile = new File(rootPath+filePath, fileName + "." + str[str.length - 1]);
multipartFile.transferTo(uploadedFile);
String imgUrl = filePath + fileName + "." + str[str.length - 1];
Map<String, Object> map = new HashMap<String, Object>();
map.put("filePath", imgUrl);
map.put("fileName", fileRealName);
imagePathList.add(map);
}
return imagePathList;
}
public boolean validateFileType(String fileName,String type){
String fileType = fileName.substring(fileName.lastIndexOf(".")+1).toLowerCase();
if(type!=null){
if(extMap.containsKey(type)){
String extType = extMap.get(type);
String extTypes[] = extType.split(",");
return Arrays.asList(extTypes).contains(fileType);
}else{
return false;
}
}else{
String extType="";
for (String value : extMap.values()) {
extType = extType+","+value;
}
String extTypes[] = extType.split(",");
return Arrays.asList(extTypes).contains(fileType);
}
}
public String initFilePath(String path)throws RuntimeException {
try {
String filePath = path + DateUtil.getFormatDate("yyyyMMdd", new Date()) + "/";
String savePath = rootPath + filePath;
savePath.replaceAll("\\\\", "/").replaceAll("//", "/");
File saveDirFile = new File(rootPath);
if (!saveDirFile.exists()) {
saveDirFile.mkdirs();
}
File dirFile = new File(savePath);
if (!dirFile.exists()) {
dirFile.mkdirs();
}
return filePath;
}catch (RuntimeException e){
throw new RuntimeException("创建文件异常:错误的文件路径。");
}
}
}