package com.wishcome.controller;
import com.wishcome.constants.Constants;
import com.wishcome.domain.SysAdmin;
import com.wishcome.exception.GlobalException;
import com.wishcome.util.*;
import io.swagger.annotations.ApiOperation;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.util.MultiValueMap;
import org.springframework.web.bind.annotation.*;
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.*;
import java.net.URLEncoder;
import java.util.ArrayList;
import java.util.List;
import java.util.Objects;
@RestController
@RequestMapping("/api/pub")
public class DownLoadUtils {
@Value("${upload.imagesPath}")
private String imagesPath;
@Value("${upload.filesPath}")
private String filesPath;
@Value("${download.url}")
private String downloadUrl;
@Autowired
private TokenComponent tokenComponent;
public static String getContentType(String fileExt) {
switch (fileExt) {
case ".doc":
return "application/msword";
case "docx":
return "application/vnd.openxmlformats-officedocument.wordprocessingml.document";
case ".rtf":
return "application/rtf";
case ".xls":
return "application/vnd.ms-excel";
case ".xlsx":
return "application/vnd.openxmlformats-officedocument.spreadsheetml.sheet";
case ".ppt":
return "application/vnd.ms-powerpoint";
case ".pptx":
return "application/vnd.openxmlformats-officedocument.presentationml.presentation";
case ".pdf":
return "application/pdf";
case ".swf":
return "application/x-shockwave-flash";
case ".rar":
return "application/octet-stream";
case ".zip":
return "application/x-zip-compressed";
case ".mp3":
return "audio/mpeg";
case ".gif":
return "image/gif";
case ".png":
return "image/png";
case ".jpeg":
case ".jpg":
case ".jpe":
case ".bmp":
return "image/jpeg";
case ".txt":
return "text/plain";
case ".svg":
return " text/xml";
default:
return "application/octet-stream";
}
}
@GetMapping("/files/{filePath}")
public void downloadLocalFiles(@PathVariable("filePath")String filePath, String fileNameNow, HttpServletResponse httpServletResponse) {
httpServletResponse.reset();
if (!Objects.isNull(fileNameNow)) {
try {
fileNameNow = URLEncoder.encode(fileNameNow, "UTF-8");
httpServletResponse.addHeader("Content-Disposition", "attachment; filename=\"" + fileNameNow + "\"");
} catch (UnsupportedEncodingException e) {
e.printStackTrace();
}
}
if(filePath.lastIndexOf(".")==-1||filePath.contains("/../")){
return;
}
String fileExt = filePath.substring(filePath.lastIndexOf(".")).trim().toLowerCase();
InputStream fileInputStream = null;
OutputStream outStream;
httpServletResponse.setContentType(getContentType(fileExt));
try {
fileInputStream = new FileInputStream(filesPath + filePath);
outStream = httpServletResponse.getOutputStream();
byte[] bytes = new byte[1024];
int len = 0;
while ((len = fileInputStream.read(bytes)) != -1) {
outStream.write(bytes, 0, len);
}
fileInputStream.close();
outStream.close();
outStream.flush();
} catch (IOException e) {
e.printStackTrace();
}
}
@GetMapping("/images/**")
public void downloadLocalImages(String filePath, String fileNameNow, HttpServletResponse httpServletResponse) {
httpServletResponse.reset();
if (!Objects.isNull(fileNameNow)) {
try {
fileNameNow = URLEncoder.encode(fileNameNow, "UTF-8");
httpServletResponse.addHeader("Content-Disposition", "attachment; filename=\"" + fileNameNow + "\"");
} catch (UnsupportedEncodingException e) {
e.printStackTrace();
}
}
String fileExt = filePath.substring(filePath.lastIndexOf(".")).trim().toLowerCase();
InputStream fileInputStream = null;
OutputStream outStream;
httpServletResponse.setContentType(getContentType(fileExt));
try {
fileInputStream = new FileInputStream(imagesPath + filePath);
outStream = httpServletResponse.getOutputStream();
byte[] bytes = new byte[1024];
int len = 0;
while ((len = fileInputStream.read(bytes)) != -1) {
outStream.write(bytes, 0, len);
}
fileInputStream.close();
outStream.close();
outStream.flush();
} catch (IOException e) {
e.printStackTrace();
}
}
@ApiOperation("图片上传")
@PostMapping("/uploadImages")
public ResponseObject uploadImageFile(MultipartHttpServletRequest request, HttpServletRequest httpServletRequest) {
String token = httpServletRequest.getHeader(Constants.HEADER_TOKEN_X);
SysAdmin webAdmin = tokenComponent.getWebAdmin(token);
if(Objects.isNull(webAdmin)){
throw new GlobalException(401, "登录过期");
}
List<String> objectPaths = new ArrayList<>();
MultiValueMap<String, MultipartFile> multiFileMap = request.getMultiFileMap();
multiFileMap.keySet().forEach((key) -> {
multiFileMap.get(key).forEach((multipartFile) -> {
if (StringUtils.isEmpty(multipartFile.getOriginalFilename())) return;
long mb = multipartFile.getSize() / 1024 / 1024;
if (mb > 2) {
throw new GlobalException(709, "图片最大为 2 mb");
}
String[] split = multipartFile.getOriginalFilename().split("\\.");
String originalFilename = System.currentTimeMillis() + "_" + split[0];
originalFilename = Sha256Util.getSHA256(originalFilename);
String fileType = split[split.length - 1];
if (!fileType.equals("bmp") && !fileType.equals("gif") && !fileType.equals("jpg") && !fileType.equals("png") && !fileType.equals("jpeg")) {
throw new GlobalException(500, "文件格式不正确");
}
originalFilename = originalFilename + "." + fileType;
String path = imagesPath + File.separator + webAdmin.getId() + File.separator;
File directory = new File(path);
if (!directory.exists()) {
directory.mkdirs();
}
path += originalFilename;
try {
BufferedInputStream bis = new BufferedInputStream(multipartFile.getInputStream());
BufferedOutputStream bos = new BufferedOutputStream(new FileOutputStream(path));
int b;
while ((b = bis.read()) != -1) {
bos.write(b);
}
objectPaths.add(downloadUrl + "/api/pub/images/?filePath=" + "/" + webAdmin.getId() + "/" + originalFilename);
bos.close();
bis.close();
} catch (FileNotFoundException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
});
});
return ResponseObjectUtil.success(objectPaths.size() > 0 ? objectPaths : "");
}
}
【推荐】国内首个AI IDE,深度理解中文开发场景,立即下载体验Trae
【推荐】编程新体验,更懂你的AI,立即体验豆包MarsCode编程助手
【推荐】抖音旗下AI助手豆包,你的智能百科全书,全免费不限次数
【推荐】轻量又高性能的 SSH 工具 IShell:AI 加持,快人一步
· 分享4款.NET开源、免费、实用的商城系统
· 全程不用写代码,我用AI程序员写了一个飞机大战
· MongoDB 8.0这个新功能碉堡了,比商业数据库还牛
· 白话解读 Dapr 1.15:你的「微服务管家」又秀新绝活了
· 上周热点回顾(2.24-3.2)
2022-03-03 MySql中插入系统当前时间的方式和Oracle中并不相同: