FileController
/**
* 文件管理
* @Date:2024/5/9 8:57
*/
@RestController
@RequestMapping("admin/File")
@RequiredArgsConstructor(onConstructor = @__(@Autowired))
public class FileController {
private final FileService fileService;
/**
* 文件上传
* @return
*/
@PostMapping("uploadFile")
@OperLog(module = "文件上传", type = OperationType.SELECT, desc = "文件上传")
public R uploadFile(@RequestParam(name = "file") MultipartFile file, HttpServletRequest request) throws Exception {
return fileService.uploadFile(file);
}
/**
* 图片上传
* @return
*/
@PostMapping("uploadImg")
@OperLog(module = "图片上传", type = OperationType.SELECT, desc = "图片上传")
public R uploadImg(@RequestParam(name = "file") MultipartFile file, HttpServletRequest request) throws Exception {
return fileService.uploadImgFile(file,request);
}
/**
* 查看图片
* @return
*/
@PostMapping("showImg")
@OperLog(module = "查看图片", type = OperationType.SELECT, desc = "图片上传")
public void showImg(@RequestParam(name = "imgPath") String imgPath, HttpServletResponse response) throws Exception {
fileService.showImg(imgPath,response);
}
}
FileService
public interface FileService {
public R uploadFile(MultipartFile file);
public R uploadImgFile(MultipartFile file, HttpServletRequest request);
public void showImg(String imgPath, HttpServletResponse response);
}
FileServiceImpl
import com.alibaba.fastjson.JSON;
import com.xxxxx.iotdevice.common.core.utils.file.UploadUtil;
import com.xxxxx.iotdevice.common.core.vo.R;
import com.xxxxx.iotdevice.common.data.admin.file.service.FileService;
import org.apache.commons.collections.MapUtils;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.core.io.ByteArrayResource;
import org.springframework.http.*;
import org.springframework.http.converter.StringHttpMessageConverter;
import org.springframework.stereotype.Service;
import org.springframework.util.LinkedMultiValueMap;
import org.springframework.util.MultiValueMap;
import org.springframework.web.client.RestTemplate;
import org.springframework.web.multipart.MultipartFile;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.nio.charset.StandardCharsets;
import java.util.HashMap;
import java.util.Map;
@Service
public class FileServiceImpl implements FileService {
@Value("${app.adminUrl}")
public String url;
@Value("${app.profile}")
public String filePath;
@Override
public R uploadFile(MultipartFile file) {
Map<String, Object> stringObjectMap = UploadUtil.fileUpload(file, filePath+"file");
return R.ok().result(stringObjectMap);
}
@Override
public R uploadImgFile(MultipartFile file, HttpServletRequest request) {
String token = request.getHeader("Admin-Token");
// 地址
String sapUrl = url+"/admin-api/infra/file/xxxx";
RestTemplate restTemplate = new RestTemplate();
try {
ByteArrayResource fileAsResource = new ByteArrayResource(file.getBytes()) {
@Override
public String getFilename() {
return file.getOriginalFilename();
}
};
// 添加文件部分
ContentDisposition contentDisposition = ContentDisposition
.builder("form-data")
.name("file") // 与后端的字段名匹配
.filename(file.getOriginalFilename())
.build();
HttpHeaders fileHeaders = new HttpHeaders();
fileHeaders.setContentDisposition(contentDisposition);
fileHeaders.setContentType(MediaType.parseMediaType(file.getContentType()));
// 封装文件内容
HttpEntity<ByteArrayResource> fileEntity = new HttpEntity<>(fileAsResource, fileHeaders);
MultiValueMap<String, Object> bodyMap = new LinkedMultiValueMap<>();
bodyMap.add("file", fileEntity);
HttpHeaders headers = new HttpHeaders();
headers.setContentType(MediaType.MULTIPART_FORM_DATA);// 使用multipart/form-data
headers.set("Authorization", token);
// 创建HttpEntity,它只包含请求头和请求体
HttpEntity<MultiValueMap<String, Object>> entity = new HttpEntity<>(bodyMap, headers);
restTemplate.getMessageConverters().set(1, new StringHttpMessageConverter(StandardCharsets.UTF_8));//解决乱码问题
String strbody = restTemplate.postForEntity(sapUrl, entity, String.class).getBody();
Map<String, Object> reqMap = JSON.parseObject(strbody, Map.class);//JSONObject
if ((int)reqMap.get("code")==0){
return R.ok().message("上传成功").result(reqMap);
}
return R.error().message("上传失败").result(reqMap);
} catch (Exception e) {
throw new RuntimeException(e);
}
}
@Override
public void showImg(String imgPath, HttpServletResponse response) {
UploadUtil.showImg(imgPath,response);
}
}
UploadUtil
package com.xxxx.iotdevice.common.core.utils.file;
import cn.hutool.core.date.DateUtil;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.web.multipart.MultipartFile;
import javax.servlet.ServletOutputStream;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.*;
import java.net.MalformedURLException;
import java.net.URL;
import java.util.*;
/**
* 文件上传
*/
public class UploadUtil {
/**
* 文件上传
*
* @param
* @param fileDir 文件保存路径(在upload目录下的路径,如:fileDir=user/logo,则文件保存到项目的upload/user/logo目录中)
* @param fileType 文件类型,对应FileUtil中定义的文件类型(imgType,appType,textType,videoType,mediaType,compressedType,attachType(附件包含图片,视频,音频,文件,压缩文件))
* @return
*/
public static Map<String, Object> fileUpload(MultipartFile file, String fileDir) {
Map<String, Object> jsonMap = new HashMap<String, Object>();
// MultipartHttpServletRequest multipartRequest = (MultipartHttpServletRequest) request;
// MultipartFile file = multipartRequest.getFile("file");
//保存
if (file != null && StringUtils.isNotBlank(file.getOriginalFilename())) {
String originalFilename = file.getOriginalFilename();
//校验文件类型
boolean check = true;
//上传文件后缀名称
String extendName = originalFilename.substring(originalFilename.lastIndexOf("."));
/*校验: 文件格式是否符合要求*/
if (!Arrays.asList(UploadCheckUtils.FILE_SUFFIX_SUPPORT).contains(extendName.toLowerCase(Locale.ROOT))) {
check=false;
}
if (check) {
//String bannerId = UUID.randomUUID().toString();
//新文件名称
String newFileName = DateUtil.current() + extendName;
//应用的真实路径
//String realContextPath = request.getSession().getServletContext().getRealPath("/");
String relativePath = fileDir + "/" + DateUtil.format(new Date(),"yyyyMMdd") + "/";
//新文件所属目录
File destFile = new File(relativePath);
if (!destFile.exists()) {
destFile.mkdirs();
}
try {
String fileUrl = relativePath + newFileName;
//新文件
File normalFile = new File(destFile, newFileName);
file.transferTo(normalFile);
jsonMap.put("resCode", 0);
jsonMap.put("resMsg", "上传成功");
jsonMap.put("fileUrl", fileUrl);
} catch (Exception e) {
jsonMap.put("resCode", 1);
jsonMap.put("resMsg", "上传失败");
e.printStackTrace();
}
} else {
jsonMap.put("resCode", 1);
jsonMap.put("resMsg", "您上传的格式不正确");
}
} else {
jsonMap.put("resCode", 1);
jsonMap.put("resMsg", "未选择文件或文件名为空");
}
return jsonMap;
}
//链接url下载图片
public static int downloadPicture(String urlList,String path) {
URL url = null;
try {
url = new URL(urlList);
DataInputStream dataInputStream = new DataInputStream(url.openStream());
FileOutputStream fileOutputStream = new FileOutputStream(new File(path));
ByteArrayOutputStream output = new ByteArrayOutputStream();
byte[] buffer = new byte[1024];
int length;
while ((length = dataInputStream.read(buffer)) > 0) {
output.write(buffer, 0, length);
}
fileOutputStream.write(output.toByteArray());
dataInputStream.close();
fileOutputStream.close();
} catch (MalformedURLException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
return 0;
}
// 回显图片
public static void showImg(String imgUrl, HttpServletResponse response) {
// 获取图片的当前路径 放入读
FileInputStream fis = null;
// 用response 获取一个写对象的流
ServletOutputStream os = null;
try {
fis = new FileInputStream(imgUrl);
os = response.getOutputStream();
// 提高读写的速度
byte[] b = new byte[1024];
// 边读边写
while (fis.read(b) != -1) {
os.write(b);
}
} catch (FileNotFoundException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
} finally {
try {
if (os != null) {
os.close();
}
if (fis != null) {
fis.close();
}
} catch (IOException e) {
e.printStackTrace();
}
}
}
// 下载
public static void downLoad(String filePath, HttpServletRequest request, HttpServletResponse response) {
//设置文件的MiMe类型
response.setContentType(request.getSession().getServletContext().getMimeType(filePath));
//设置content-disposition
response.setHeader("Content-Disposition", "attachment;filename=" + filePath);
//读取目标文件,通过response将目标文件写到客户
try {
// 读取文件
InputStream in = new FileInputStream(filePath);
OutputStream out = response.getOutputStream();
//写文件
byte[] b = new byte[1024];
while (in.read(b) != -1) {
out.write(b);
}
in.close();
out.close();
} catch (Exception e) {
e.printStackTrace();
}
}
}