服务端:
下载:
/**
* 文件下载请求
*/
@GetMapping("/download/{imageId}")
@ApiOperation("下载")
public void downloadFile(@PathVariable("imageId") Long imageId, HttpServletResponse response) throws IOException {
byte[] bytes = sysFileService.downloadImage(imageId, response);
ServletOutputStream outputStream = null;
try {
outputStream = response.getOutputStream();
response.setContentType("application/octet-stream");
outputStream.write(bytes);
} catch (IOException e) {
e.printStackTrace();
} finally {
try {
outputStream.flush();
outputStream.close();
} catch (IOException e) {
e.printStackTrace();
}
}
}
@Override
public byte[] downloadImage(Long imageId, HttpServletResponse response) {
IotpMonitorPointPicture byId = monitorPointPictureService.getById(imageId);
if (byId == null) {
throw new IotdeviceCheckException(400, "文件不存在!");
}
return this.fileDownloadSetting(byId.getPath(), byId.getName(), response);
}
public byte[] fileDownloadSetting(String path, String fileName, HttpServletResponse response) {
try {
// path是指欲下载的文件的路径。
File file = new File(path);
if (!file.exists()) {
throw new IotdeviceCheckException(500, "文件错误");
}
// 取得文件的后缀名。
// String ext = byId.getName().substring(byId.getName().lastIndexOf(".") + 1).toUpperCase();
// 以流的形式下载文件。
InputStream fis = new BufferedInputStream(new FileInputStream(file));
byte[] buffer = new byte[fis.available()];
fis.read(buffer);
fis.close();
// 清空response
response.reset();
// 设置response的Header
response.addHeader("Content-Disposition", "attachment;filename=" + URLEncoder.encode(fileName, "UTF-8"));
response.setCharacterEncoding("UTF-8");
response.addHeader("Content-Length", "" + file.length());
return buffer;
} catch (Exception e) {
e.printStackTrace();
throw new IotdeviceCheckException(500, "服务器内部错误");
}
}
上传:
/**
* 文件上传请求
*/
@PostMapping("/upload")
@ApiOperation("上传")
public R<Long> imageUpload(Long uploader, MultipartFile image) {
if (image == null) {
return R.fail("图片上传失败,图片文件不能为null");
}
try {
// 上传并返回访问地址
Long sysFile = sysFileService.uploadImage(image, uploader);
return R.ok(sysFile);
} catch (Exception e) {
log.error("上传文件失败", e);
return R.fail(e.getMessage());
}
}
private static final List<String> IMAGE_TYPES = Arrays.asList("image/jpeg", "image/pjpeg", "image/bmp", "image/gif",
"image/png", "image/x-png");
@Override
public Long uploadImage(MultipartFile image, Long uploader) {
String originalFilename = image.getOriginalFilename();
// 校验文件的类型
String contentType = this.getMimeType(image);
if (!IMAGE_TYPES.contains(contentType)) {
// 文件类型不合法,直接返回null
throw new IotdeviceCheckException(400, "文件类型不合法!");
}
try {
// 校验文件的内容
BufferedImage bufferedImage = ImageIO.read(image.getInputStream());
if (bufferedImage == null) {
throw new IotdeviceCheckException(400, "文件内容不合法" + originalFilename);
}
IotpMonitorPointPicture monitorPointPicture = new IotpMonitorPointPicture();
monitorPointPicture.setCreateBy(uploader);
monitorPointPictureService.save(monitorPointPicture);
// 保存到服务器
String name = FileUploadUtils.upload(localFilePath, image);
// 生成url地址,返回
String url = domain + localFilePrefix + name;
SysFile sysFile = new SysFile();
sysFile.setUrl(url);
monitorPointPicture.setUrl(url);
monitorPointPicture.setPath(localFilePath + name);
monitorPointPicture.setName(originalFilename);
sysFile.setId(monitorPointPicture.getId());
monitorPointPictureService.updateById(monitorPointPicture);
return monitorPointPicture.getId();
} catch (IOException e) {
e.printStackTrace();
throw new IotdeviceCheckException(500, "服务器内部错误" + originalFilename);
}
}
/**
* 获取文件类型
*
* @param file
* @return
*/
private String getMimeType(MultipartFile file) {
AutoDetectParser parser = new AutoDetectParser();
parser.setParsers(new HashMap<MediaType, Parser>());
Metadata metadata = new Metadata();
metadata.add(TikaMetadataKeys.RESOURCE_NAME_KEY, file.getName());
try (InputStream stream = file.getInputStream()) {
parser.parse(stream, new DefaultHandler(), metadata, new ParseContext());
} catch (Exception e) {
throw new RuntimeException();
}
return metadata.get(HttpHeaders.CONTENT_TYPE);
}
获取文件类型需要引入一下依赖
<dependency>
<groupId>org.apache.tika</groupId>
<artifactId>tika-core</artifactId>
<version>1.20</version>
</dependency>
FeignClient接口设定:
重点:Response 是feign.Response;
import feign.Response;
/**
* 文件下载请求
*/
@GetMapping(value = "/download/{imageId}")
public Response downloadFile(@PathVariable("imageId") Long imageId);
/**
* 文件上传请求
*/
@PostMapping(value = "/upload", consumes = MediaType.MULTIPART_FORM_DATA_VALUE)
public R<Long> imageUpload(@RequestParam("uploader") Long uploader, @RequestBody MultipartFile image);
调用端:
/**
* 文件下载请求
*/
@GetMapping("/download/{imageId}")
@ApiOperation("下载")
public void downloadFile(@PathVariable("imageId") Long imageId, HttpServletResponse response) throws IOException {
InputStream inputStream = null;
OutputStream outputStream = null;
try {
// feign文件下载
Response responseFromRemote = imageFileService.downloadFile(imageId);
if(responseFromRemote == null) {
return;
}
Response.Body body = responseFromRemote.body();
inputStream = body.asInputStream();
outputStream = response.getOutputStream();
Map<String, Collection<String>> headers = responseFromRemote.headers();
if (headers.containsKey("Content-Disposition")) {
response.addHeader("Content-Disposition", headers.get("Content-Disposition").iterator().next());
}
response.setCharacterEncoding("UTF-8");
if (headers.containsKey("Content-Length")) {
response.addHeader("Content-Length", headers.get("Content-Length").iterator().next());
}
response.setContentType("application/octet-stream");
// byte[] b = new byte[inputStream.available()];
byte[] buffer = new byte[1024 * 8];
int count = 0;
while ((count = inputStream.read(buffer)) != -1) {
outputStream.write(buffer, 0, count);
}
outputStream.flush();
} catch (IOException e) {
e.printStackTrace();
} finally {
if (inputStream != null) {
try {
inputStream.close();
} catch (IOException e) {
e.printStackTrace();
}
}
if (outputStream != null) {
try {
outputStream.close();
} catch (IOException e) {
e.printStackTrace();
}
}
}
}
/**
* 文件上传请求
*/
@PostMapping("/upload")
@ApiOperation("上传")
public R<Long> imageUpload(Long uploader, MultipartFile image) {
if (image == null) {
return R.fail("图片上传失败,图片文件不能为null");
}
return imageFileService.imageUpload(uploader, image);
}