|
@@ -0,0 +1,80 @@
|
|
|
+package com.caimei.service.impl;
|
|
|
+
|
|
|
+import com.caimei.mapper.FileMapper;
|
|
|
+import com.caimei.service.DownloadService;
|
|
|
+import com.caimei.utils.OSSUtils;
|
|
|
+import lombok.extern.slf4j.Slf4j;
|
|
|
+import org.springframework.stereotype.Service;
|
|
|
+
|
|
|
+import javax.annotation.Resource;
|
|
|
+import javax.servlet.http.HttpServletRequest;
|
|
|
+import javax.servlet.http.HttpServletResponse;
|
|
|
+import java.io.File;
|
|
|
+import java.io.FileInputStream;
|
|
|
+import java.io.IOException;
|
|
|
+import java.io.OutputStream;
|
|
|
+import java.net.URLEncoder;
|
|
|
+
|
|
|
+/**
|
|
|
+ * Description
|
|
|
+ *
|
|
|
+ * @author : Aslee
|
|
|
+ * @date : 2021/7/9
|
|
|
+ */
|
|
|
+@Slf4j
|
|
|
+@Service
|
|
|
+public class DownloadServiceImpl implements DownloadService {
|
|
|
+
|
|
|
+ @Resource
|
|
|
+ private FileMapper fileMapper;
|
|
|
+
|
|
|
+ @Override
|
|
|
+ public void downloadFile(String ossName, String fileName, HttpServletRequest request, HttpServletResponse response) throws IOException {
|
|
|
+ OSSUtils.downFile("authFile/", ossName, fileName);
|
|
|
+ download(request, response, fileName);
|
|
|
+ }
|
|
|
+
|
|
|
+ public void download(HttpServletRequest request, HttpServletResponse response, String fileName) throws IOException {
|
|
|
+ File file = new File("./" + fileName);
|
|
|
+ // 文件存在才下载
|
|
|
+ if (file.exists()) {
|
|
|
+ OutputStream out = null;
|
|
|
+ FileInputStream in = null;
|
|
|
+ try {
|
|
|
+ // 1.读取要下载的内容
|
|
|
+ in = new FileInputStream(file);
|
|
|
+
|
|
|
+ // 2. 告诉浏览器下载的方式以及一些设置
|
|
|
+ // 解决文件名乱码问题,获取浏览器类型,转换对应文件名编码格式,IE要求文件名必须是utf-8, firefo要求是iso-8859-1编码
|
|
|
+ String agent = request.getHeader("user-agent");
|
|
|
+ if (agent.contains("FireFox")) {
|
|
|
+ fileName = new String(fileName.getBytes("UTF-8"), "iso-8859-1");
|
|
|
+ } else {
|
|
|
+ fileName = URLEncoder.encode(fileName, "UTF-8");
|
|
|
+ }
|
|
|
+ // 设置下载文件的mineType,告诉浏览器下载文件类型
|
|
|
+ String mineType = request.getServletContext().getMimeType(fileName);
|
|
|
+ response.setContentType(mineType);
|
|
|
+ // 设置一个响应头,无论是否被浏览器解析,都下载
|
|
|
+ response.setHeader("Content-disposition", "attachment; filename=" + fileName);
|
|
|
+ // 将要下载的文件内容通过输出流写到浏览器
|
|
|
+ out = response.getOutputStream();
|
|
|
+ int len = 0;
|
|
|
+ byte[] buffer = new byte[1024];
|
|
|
+ while ((len = in.read(buffer)) > 0) {
|
|
|
+ out.write(buffer, 0, len);
|
|
|
+ }
|
|
|
+ } catch (IOException e) {
|
|
|
+ e.printStackTrace();
|
|
|
+ } finally {
|
|
|
+ if (out != null) {
|
|
|
+ out.close();
|
|
|
+ }
|
|
|
+ if (in != null) {
|
|
|
+ in.close();
|
|
|
+ }
|
|
|
+ file.delete();
|
|
|
+ }
|
|
|
+ }
|
|
|
+ }
|
|
|
+}
|