package com.zzg.web.controller.common;
|
|
import cn.hutool.core.lang.Dict;
|
import cn.hutool.core.text.StrPool;
|
import com.zzg.common.core.domain.AjaxResult;
|
import com.zzg.system.service.system.IFileService;
|
import io.swagger.annotations.Api;
|
import io.swagger.annotations.ApiOperation;
|
import org.slf4j.Logger;
|
import org.slf4j.LoggerFactory;
|
import org.springframework.beans.factory.annotation.Value;
|
import org.springframework.web.bind.annotation.*;
|
import org.springframework.web.multipart.MultipartFile;
|
|
import javax.annotation.Resource;
|
import javax.servlet.http.HttpServletRequest;
|
import javax.servlet.http.HttpServletResponse;
|
import java.io.*;
|
import java.net.URLEncoder;
|
import java.util.Arrays;
|
import java.util.List;
|
|
/**
|
* 文件上传
|
*/
|
@RestController
|
@Api(tags = "文件上传,下载")
|
@RequestMapping("/file")
|
public class FileController {
|
private static final Logger log = LoggerFactory.getLogger(FileController.class);
|
|
@Resource
|
private IFileService fileService;
|
@Value("${ruoyi.upload}")
|
String landexp;
|
|
@ApiOperation(value = "文件上传", notes = "返回文件的名字,下载文件时可以通过文件的名字下载!")
|
@PostMapping("/public/upload")
|
public List<Dict> publicUpload(@RequestParam("file") MultipartFile[] file, HttpServletRequest req) {
|
// return fileService.upload2Temp(Arrays.asList(file), req);
|
List<MultipartFile> fileList = Arrays.asList(file);
|
if (fileList.size() > 10) {
|
throw new RuntimeException("一次最多上传10份文件");
|
}
|
return fileService.upload2Temp(fileList, req);
|
}
|
|
|
@GetMapping("/public/download")
|
@ApiOperation(value = "文件下载", notes = "单文件")
|
public AjaxResult download(@RequestParam String filename, HttpServletResponse response) throws IOException, InterruptedException {
|
File absFile = new File(landexp + filename);
|
if (absFile.exists()) {
|
//协议文件名称没有下划线,只有upload路径--pload/征地拆迁住房安置协议-许肖肖-204125.pdf
|
filename = filename.substring(filename.lastIndexOf(StrPool.SLASH) + 1);
|
//不同文件
|
filename = filename.substring(filename.indexOf(StrPool.UNDERLINE) + 1);
|
response.setContentType("application/octet-stream;charset=utf-8");
|
response.addHeader("Content-Disposition", "attachment; filename=" +
|
URLEncoder.encode(filename, "UTF-8"));
|
FileInputStream fileInputStream = new FileInputStream(absFile);
|
int len = 0;
|
byte[] buffer = new byte[1024];
|
OutputStream outputStream = response.getOutputStream();
|
while ((len = fileInputStream.read(buffer)) > 0) {
|
outputStream.write(buffer, 0, len);
|
}
|
fileInputStream.close();
|
outputStream.flush();
|
outputStream.close();
|
return AjaxResult.success();
|
} else {
|
log.error("下载文件地址:" + filename);
|
return AjaxResult.error("文件不存在!");
|
}
|
}
|
|
}
|