文件下载

This commit is contained in:
haozq 2024-11-09 20:42:00 +08:00
parent 9e59aa7097
commit 9218b8c3ed
7 changed files with 383 additions and 3 deletions

12
pom.xml
View File

@ -34,6 +34,18 @@
<artifactId>mybatis-spring-boot-starter</artifactId>
<version>2.1.3</version>
</dependency>
<dependency>
<groupId>org.apache.httpcomponents</groupId>
<artifactId>httpclient</artifactId>
</dependency>
<dependency>
<groupId>org.apache.httpcomponents</groupId>
<artifactId>httpmime</artifactId>
</dependency>
<dependency>
<groupId>org.projectlombok</groupId>
<artifactId>lombok</artifactId>
</dependency>
<dependency>
<groupId>com.alibaba</groupId>
<artifactId>druid-spring-boot-starter</artifactId>

View File

@ -7,6 +7,8 @@ import cn.hutool.core.convert.Convert;
import com.bonus.gzgqj.business.plan.entity.*;
import com.bonus.gzgqj.business.plan.service.PlanApplicationService;
import com.bonus.gzgqj.business.plan.service.PlanOutService;
import com.bonus.gzgqj.business.utils.FileUploadService;
import com.bonus.gzgqj.business.utils.SystemUtils;
import com.bonus.gzgqj.manager.annotation.DecryptAndVerify;
import com.bonus.gzgqj.manager.common.util.ServletUtils;
import com.bonus.gzgqj.manager.core.entity.EncryptedReq;
@ -15,18 +17,24 @@ import com.bonus.gzgqj.manager.webResult.StringUtils;
import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.io.FileUtils;
import org.apache.poi.ss.usermodel.Workbook;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.*;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;
import javax.servlet.ServletOutputStream;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.File;
import java.net.URLEncoder;
import java.util.ArrayList;
import java.util.List;
import org.springframework.core.io.Resource;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;
/**
* 出库 控制层
*
@ -43,6 +51,8 @@ public class PlanOutController {
@Autowired
private PlanApplicationService planService;
@Autowired
private FileUploadService fileUploadService;
/**
* 发货 统计查询
* @return
@ -296,4 +306,45 @@ public class PlanOutController {
/**
* "中文名称"文件下载
*/
@GetMapping("/download")
public ResponseEntity<byte[]> fileDownload(HttpServletRequest request, String fileId) throws Exception{
//指定下载的文件根路径
String dirPath = SystemUtils.getUploadPath();
String filename=fileUploadService.getFilePath(fileId);
//创建该文件对象
File file = new File(dirPath +filename);
//设置响应头
HttpHeaders headers = new HttpHeaders();
//通知浏览器以下载方式打开(下载前对文件名进行转码)
filename=getFilename(request,filename);
headers.setContentDispositionFormData("attachment",filename);
//定义以流的形式下载返回文件数据
headers.setContentType(MediaType.APPLICATION_OCTET_STREAM);
try {return new ResponseEntity<>(FileUtils.readFileToByteArray(file),
headers, HttpStatus.OK);} catch (Exception e) {e.printStackTrace();
return new ResponseEntity<byte[]>(e.getMessage().getBytes(),
HttpStatus.EXPECTATION_FAILED);
}
}
//根据浏览器的不同进行编码设置返回编码后的文件名
private String getFilename(HttpServletRequest request,String filename)
throws Exception {
//IE不同版本User-Agent中出现的关键词
String[] IEBrowserKeyWords = {"MSIE", "Trident", "Edge"};
//获取请求头代理信息
String userAgent = request.getHeader("User-Agent");
for (String keyWord : IEBrowserKeyWords) {
if (userAgent.contains(keyWord)) {
//IE内核浏览器统一为UTF-8编码显示并对转换的+进行更正
return URLEncoder.encode(filename, "UTF-8").replace("+"," ");
}}
//火狐等其他浏览器统一为ISO-8859-1编码显示
return new String(filename.getBytes("UTF-8"), "ISO-8859-1");
}
}

View File

@ -22,4 +22,11 @@ public interface FileUploadMapper {
* @return
*/
List<FileUploadVo> getFileList(FileUploadVo vo);
/**
* 查询文件路径
* @param fileId
* @return
*/
String getFilePath(String fileId);
}

View File

@ -88,4 +88,13 @@ public class FileUploadService {
}
public String getFilePath(String fileId) {
try {
return mapper.getFilePath(fileId);
}catch (Exception e){
log.error(e.toString(),e);
}
return "";
}
}

View File

@ -0,0 +1,294 @@
package com.bonus.gzgqj.business.utils;
import freemarker.template.Configuration;
import freemarker.template.Template;
import org.apache.commons.io.IOUtils;
import javax.servlet.ServletOutputStream;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.*;
import java.net.URLEncoder;
import java.nio.file.Files;
import java.nio.file.Path;
import java.nio.file.Paths;
import java.util.Map;
import java.util.Objects;
/**
* @author 黑子
* @Auther: ccw
* @Date: 2021/07/22/9:57
* @description:
*/
public class WordUtils {
public static String pdf_fix="pdf";
public static String doc_fix="doc";
public static String docx_fix="docx";
/**
*
*/
private static Configuration configuration = null;
static {
configuration = new Configuration(Configuration.VERSION_2_3_30);
configuration.setDefaultEncoding("utf-8");
configuration.setClassForTemplateLoading(WordUtils.class, "/download/");
}
private WordUtils() {
throw new AssertionError();
}
public static void exportMillCertificateWord(HttpServletRequest request, HttpServletResponse response, Map map, String title, String ftlFile) throws IOException {
Template freemarkerTemplate = configuration.getTemplate(ftlFile);
File file = null;
InputStream fin = null;
ServletOutputStream out = null;
try {
// 调用工具类的createDoc方法生成Word文档
file = createDoc(map, freemarkerTemplate);
fin = new FileInputStream(file);
response.setCharacterEncoding("utf-8");
response.setContentType("application/msword");
// 设置浏览器以下载的方式处理该文件名
String fileName = title + ".docx";
response.setHeader("Content-Disposition", "attachment;filename="
.concat(String.valueOf(URLEncoder.encode(fileName, "UTF-8"))));
out = response.getOutputStream();
byte[] buffer = new byte[512];
int bytesToRead = -1;
// 通过循环将读入的Word文件的内容输出到浏览器中
while ((bytesToRead = fin.read(buffer)) != -1) {
out.write(buffer, 0, bytesToRead);
}
} finally {
if (fin != null) {fin.close();}
if (out != null) {out.close();}
// 删除临时文件
if (file != null) {file.delete();}
}
}
private static File createDoc(Map<?, ?> dataMap, Template template) {
String name = "sellPlan.doc";
File f = new File(name);
Template t = template;
try {
// 这个地方不能使用FileWriter因为需要指定编码类型否则生成的Word文档会因为有无法识别的编码而无法打开
Writer w = new OutputStreamWriter(new FileOutputStream(f), "utf-8");
t.process(dataMap, w);
w.close();
} catch (Exception ex) {
ex.printStackTrace();
throw new RuntimeException(ex);
}
return f;
}
public static void exportMillCertificateWord2(HttpServletRequest request, HttpServletResponse response, Map map, String title, String ftlFile, String path) throws IOException {
Template freemarkerTemplate = configuration.getTemplate(ftlFile);
File file = null;
InputStream fin = null;
OutputStream out = null;
String uploadPath = path + "word" + File.separator;
try {
// 调用工具类的createDoc方法生成Word文档
file = createDoc(map, freemarkerTemplate);
fin = new FileInputStream(file);
File file2 = new File(uploadPath);
// 生成文件夹
if (!file2.exists()) {
file2.mkdirs();
}
String fileName = uploadPath + File.separator + title + ".doc";
out = new FileOutputStream(new File(fileName));
byte[] buffer = new byte[512];
int bytesToRead = -1;
// 通过循环将读入的Word文件的内容输出到浏览器中
while ((bytesToRead = fin.read(buffer)) != -1) {
out.write(buffer, 0, bytesToRead);
}
} finally {
if (fin != null) {fin.close();}
if (out != null) {out.close();}
// 删除临时文件
if (file != null) {file.delete();}
}
}
public static void exportPdf(HttpServletRequest request, HttpServletResponse response, String titleName, String fileName) throws IOException {
File file = null;
InputStream fin = null;
ServletOutputStream out = null;
try {
file = new File(fileName);
fin = new FileInputStream(file);
response.setCharacterEncoding("utf-8");
response.setContentType("application/pdf");
// 设置浏览器以下载的方式处理该文件名
response.setHeader("Content-Disposition", "attachment;filename="
.concat(String.valueOf(URLEncoder.encode(titleName, "UTF-8"))));
out = response.getOutputStream();
// 缓冲区
byte[] buffer = new byte[512];
int bytesToRead = -1;
// 通过循环将读入的pdf文件的内容输出到浏览器中
while ((bytesToRead = fin.read(buffer)) != -1) {
out.write(buffer, 0, bytesToRead);
}
} finally {
if (fin != null) {fin.close();}
if (out != null) {out.close();}
}
}
public static void exportFile(HttpServletRequest request, HttpServletResponse response, String fileName, byte[] decode) throws IOException {
InputStream fin = null;
ServletOutputStream out = null;
try {
fin = new ByteArrayInputStream(decode);
response.setCharacterEncoding("utf-8");
String subfix = fileName.substring(fileName.lastIndexOf(".") + 1, fileName.length());
if(Objects.equals(subfix,pdf_fix)){
response.setContentType("application/pdf");
}else if(Objects.equals(subfix,doc_fix) || Objects.equals(subfix,docx_fix)){
response.setContentType("application/msword");
}
// 设置浏览器以下载的方式处理该文件名
response.setHeader("Content-Disposition", "attachment;filename="
.concat(String.valueOf(URLEncoder.encode(fileName, "UTF-8"))));
out = response.getOutputStream();
// 缓冲区
byte[] buffer = new byte[512];
int bytesToRead = -1;
// 通过循环将读入的pdf文件的内容输出到浏览器中
while ((bytesToRead = fin.read(buffer)) != -1) {
out.write(buffer, 0, bytesToRead);
}
} finally {
if (fin != null) {fin.close();}
if (out != null) {out.close();}
}
}
/**
* @param outputDir 要下载的文件的绝对路径
* @param response HttpServletResponse
* @throws IOException
*/
public static void fileDown(String outputDir,String fileName, HttpServletResponse response) throws IOException {
File file = null;
FileInputStream is = null;
try {
response.setContentType("text/html;charset=utf-8");
response.setCharacterEncoding("UTF-8");
response.setHeader("content-disposition", "attachment;filename=\"" + URLEncoder.encode(fileName, "utf-8") + "\"");
file = new File(outputDir);
is = new FileInputStream(file);
ServletOutputStream os = response.getOutputStream();
IOUtils.copy(is, os);
} catch (IOException e) {
e.printStackTrace();
} finally {
if (is != null) {
is.close();
}
if (file != null) {
file.delete();
}
}
}
/**
* @return void
* @author cw chen
* @description 下载word文件
* @Param request
* @Param response
* @Param titleName
* @Param fileName
* @date 2023-04-17 11:07
*/
public static void exportWord(HttpServletRequest request, HttpServletResponse response, String titleName, String fileName) throws IOException {
File file = null;
InputStream fin = null;
ServletOutputStream out = null;
try {
file = new File(fileName);
fin = new FileInputStream(file);
response.setCharacterEncoding("utf-8");
response.setContentType("application/msword");
// 设置浏览器以下载的方式处理该文件名
response.setHeader("Content-Disposition", "attachment;filename="
.concat(String.valueOf(URLEncoder.encode(titleName, "UTF-8"))));
out = response.getOutputStream();
// 缓冲区
byte[] buffer = new byte[512];
int bytesToRead = -1;
// 通过循环将读入的pdf文件的内容输出到浏览器中
while ((bytesToRead = fin.read(buffer)) != -1) {
out.write(buffer, 0, bytesToRead);
}
} finally {
if (fin != null) {fin.close();}
if (out != null) {out.close();}
}
}
/**
* @return void
* @author cw chen
* @description 下载word文件
* @Param request
* @Param response
* @Param titleName
* @Param fileName
* @date 2023-04-17 11:07
*/
public static void exportVideo(HttpServletRequest request, HttpServletResponse response, String titleName, String fileName) throws IOException {
File file = null;
InputStream fin = null;
ServletOutputStream out = null;
try {
file = new File(fileName);
fin = new FileInputStream(file);
response.setCharacterEncoding("utf-8");
response.setContentType("video/mp4");
// 设置浏览器以下载的方式处理该文件名
response.setHeader("Content-Disposition", "attachment;filename="
.concat(String.valueOf(URLEncoder.encode(titleName, "UTF-8"))));
out = response.getOutputStream();
// 缓冲区
byte[] buffer = new byte[512];
int bytesToRead = -1;
// 通过循环将读入的pdf文件的内容输出到浏览器中
while ((bytesToRead = fin.read(buffer)) != -1) {
out.write(buffer, 0, bytesToRead);
}
} finally {
if (fin != null) {
fin.close();
}
if (out != null) {
out.close();
}
file.delete();
}
}
}

View File

@ -40,8 +40,8 @@ zhly:
file:
upload_path:
windows: D://files//zg_gqj//
linux: /home/zg_gqj/files//
windows: D://files/zg_gqj/
linux: /home/zg_gqj/files/

View File

@ -30,4 +30,11 @@
where own_id=#{ownId} and model_table=#{modelTable}
</select>
<select id="getFilePath" resultType="java.lang.String">
select file_url fileUrl
from bm_file_upload
WHERE id=#{id}
</select>
</mapper>