package com.ruoyi.web.controller.groundwater.monitor;
import cn.hutool.core.io.file.FileReader;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.ruoyi.common.constant.BaseConstant;
import com.ruoyi.common.core.domain.AjaxResult;
import com.ruoyi.common.utils.DownloadFileNotFoundException;
import com.ruoyi.common.utils.MissingRequestParamException;
import com.ruoyi.common.utils.file.FileUtils;
import com.ruoyi.system.domain.groundwater.BzSiteImportTemplate;
import com.ruoyi.system.service.groundwater.IBzSiteImportTemplateService;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.MediaType;
import org.springframework.validation.BindingResult;
import org.springframework.validation.FieldError;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.io.OutputStream;
import java.io.UnsupportedEncodingException;
import java.net.URLDecoder;
import java.util.Map;
/**
* <p>
* 文件下载通用前端控制器
* </p>
*
* @author
* @since 2021-8-27 16:01:36
*/
@RestController
@RequestMapping("/common/fileDownload")
public class FileDownloadController {
@Autowired
private HttpServletRequest request;
@Autowired
private HttpServletResponse response;
@Autowired
IBzSiteImportTemplateService templateService;
/**
* log
*/
private static final Logger log = LoggerFactory.getLogger(FileDownloadController.class);
/**
* <p>
* 下载文件 将文件输出到文件流
* </p>
*
* @Param: [fileDownloadParam, bindingResult]
* @Author: bestitxq
* @Date: 2019/11/16
*/
@PostMapping("/download")
public void download(@Validated @RequestBody Map<String , String> map,
BindingResult bindingResult) {
// 参数校验
if (bindingResult.hasErrors()) {
for (FieldError fieldError : bindingResult.getFieldErrors()) {
throw new MissingRequestParamException(fieldError.getField() + fieldError.getDefaultMessage(), 1);
}
}
response.setContentType("application/json;charset=UTF-8");
// 获取文件路径
String filePath = map.get("filePath");
// 获取文件名称
String fileName = filePath.substring(filePath.lastIndexOf("/") + 1, filePath.length());
FileReader fileReader = null;
// 读取文件流
try {
fileReader = new FileReader(
BaseConstant.UPLOAD_PATH() + filePath);
} catch (cn.hutool.core.io.IORuntimeException e) {
throw new DownloadFileNotFoundException(e.getMessage(), 1);
}
// 设置响应头
response.reset();
response.setContentType("application/octet-stream;charset=UTF-8");
try {
response.setHeader("Content-Disposition", "attachment;filename=" + new String(fileName.getBytes("UTF-8"),
"ISO-8859-1"));
} catch (UnsupportedEncodingException e) {
log.error(e.getMessage(), e);
throw new RuntimeException(e.getMessage(), e);
}
// 获取输出流
OutputStream fileOutputStream = null;
try {
fileOutputStream = response.getOutputStream();
fileReader.writeToStream(fileOutputStream);
} catch (IOException e) {
log.error(e.getMessage(), e);
throw new RuntimeException(e.getMessage(), e);
} finally {
if (fileOutputStream != null) {
try {
fileOutputStream.close();
} catch (IOException e) {
log.error(e.getMessage(), e);
throw new RuntimeException(e.getMessage(), e);
}
}
}
}
/**
* <p>
* 导入模板下载
* </p>
* @deprecated: 导入模板下载
* @menu 导入模板下载
*/
@PostMapping("/downTemplate")
public AjaxResult downTemplate(@RequestBody Map<String, Integer> params ) {
Integer functionType = params.get("functionType");
if (functionType == null) {
return AjaxResult.error("模板下载失败,functionType为空");
}
QueryWrapper<BzSiteImportTemplate> query = Wrappers.query();
BzSiteImportTemplate template = templateService.getById( functionType);
if(template == null){
return AjaxResult.error("为查询到模板信息");
}
String tempAbsPath = System.getProperty("user.dir") + BaseConstant.templatePath + template.getTemplatePath();
try {
// 解决中文乱码问题
tempAbsPath = URLDecoder.decode(tempAbsPath, "UTF-8");
} catch (UnsupportedEncodingException e) {
log.error(e.getMessage(), e);
throw new RuntimeException(e.getMessage(), e);
}
// 获取文件名称
String fileName = tempAbsPath.substring(tempAbsPath.lastIndexOf("/") + 1, tempAbsPath.length());
FileReader fileReader = null;
// 读取文件流
try {
fileReader = new FileReader(tempAbsPath);
} catch (cn.hutool.core.io.IORuntimeException e) {
throw new DownloadFileNotFoundException(e.getMessage(), 1);
}
// 设置响应头
response.reset();
response.setContentType("application/octet-stream;charset=UTF-8");
try {
response.setHeader("Content-Disposition", "attachment;filename=" + new String(fileName.getBytes("UTF-8"),
"ISO-8859-1"));
} catch (UnsupportedEncodingException e) {
log.error(e.getMessage(), e);
throw new RuntimeException(e.getMessage(), e);
}
// 获取输出流
try {
response.setContentType(MediaType.APPLICATION_OCTET_STREAM_VALUE);
FileUtils.setAttachmentResponseHeader(response, fileName);
FileUtils.writeBytes(tempAbsPath, response.getOutputStream());
} catch (IOException e) {
log.error(e.getMessage(), e);
throw new RuntimeException(e.getMessage(), e);
}
return null;
}
}
package com.ruoyi.common.constant;
import cn.hutool.system.SystemUtil;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Component;
/**
* <p>
* 系统基础常量
* </p>
*
* @author
* @since 2021-8-27 16:06:38
*/
@Component
public class BaseConstant {
/**
* windows路径
*/
private static String windowsPath;
/**
* linux路径
*/
private static String linuxPath;
/**
* template路径
*/
public static String templatePath;
@Value("${path.windowsPath}")
public void setWindowsPath(String windowsPath) {
BaseConstant.windowsPath = windowsPath;
}
@Value("${path.linuxPath}")
public void setLinuxPath(String linuxPath) {
BaseConstant.linuxPath = linuxPath;
}
@Value("${path.templatePath}")
public void setTemplatePath(String templatePath) {
BaseConstant.templatePath = templatePath;
}
/**
* 上传的文件相对路径前缀
*/
public final static String UPLOAD_FILE_RELATIVE_BASEPATH_PREFIX = "attachment/";
/**
* 服务器上默认的上传文件路径
* TODO 默认配置文件路径
*/
// public final static String UPLOAD_PATH = SystemUtil.getOsInfo().isWindows() ?
// "F:/site/" : "/usr/local/site/";
public final static String UPLOAD_PATH() {
return SystemUtil.getOsInfo().isWindows() ?
windowsPath : linuxPath;
}
}
# 文件上传,下载路径, excel模板路径(测试环境在 /src/main/resources/ 部署环境在 config 下)
path:
windowsPath: D:/java_file_upload/soil_site/
linuxPath: /work/shcs-jar/java_file_upload/soil_site/
templatePath: /ruoyi-admin/src/main/resources/
package com.ruoyi.system.domain.groundwater;
import com.ruoyi.common.annotation.Excel;
import io.swagger.annotations.ApiModel;
import io.swagger.annotations.ApiModelProperty;
import lombok.Data;
import java.io.Serializable;
/**
* (SiteImportTemplate)表实体类
*
* @author
* @since 2019-12-20 10:12:42
*/
@Data
@ApiModel("模板实体类对象")
public class BzSiteImportTemplate implements Serializable {
private static final long serialVersionUID=1L;
@ApiModelProperty("主键")
private Integer id;
/**
* 模板在项目中的相对路径
*/
@ApiModelProperty("模板在项目中的相对路径")
private String templatePath;
}
版权声明:本文为qq_40580129原创文章,遵循 CC 4.0 BY-SA 版权协议,转载请附上原文出处链接和本声明。