案例管理的文件下载

This commit is contained in:
xiezhijun 2021-03-06 00:15:27 +08:00
parent 0f96ebf0f2
commit f1adbb041f
7 changed files with 112 additions and 67 deletions

View File

@ -1,13 +1,16 @@
package com.stdiet.web.controller.custom; package com.stdiet.web.controller.custom;
import java.io.InputStream; import java.io.InputStream;
import java.net.URLDecoder;
import java.net.URLEncoder; import java.net.URLEncoder;
import java.util.ArrayList;
import java.util.List; import java.util.List;
import com.stdiet.common.config.AliyunOSSConfig; import com.stdiet.common.config.AliyunOSSConfig;
import com.stdiet.common.config.RuoYiConfig; import com.stdiet.common.config.RuoYiConfig;
import com.stdiet.common.constant.Constants; import com.stdiet.common.constant.Constants;
import com.stdiet.common.exception.file.FileNameLengthLimitExceededException; import com.stdiet.common.exception.file.FileNameLengthLimitExceededException;
import com.stdiet.common.utils.DateUtils;
import com.stdiet.common.utils.StringUtils; import com.stdiet.common.utils.StringUtils;
import com.stdiet.common.utils.file.FileUploadUtils; import com.stdiet.common.utils.file.FileUploadUtils;
import com.stdiet.common.utils.file.FileUtils; import com.stdiet.common.utils.file.FileUtils;
@ -15,15 +18,9 @@ import com.stdiet.common.utils.file.MimeTypeUtils;
import com.stdiet.common.utils.oss.AliyunOSSUtils; import com.stdiet.common.utils.oss.AliyunOSSUtils;
import com.stdiet.custom.domain.SysCustomerCaseFile; import com.stdiet.custom.domain.SysCustomerCaseFile;
import com.stdiet.custom.dto.request.FileRequest; import com.stdiet.custom.dto.request.FileRequest;
import com.sun.deploy.net.HttpResponse;
import io.swagger.models.auth.In;
import org.aspectj.weaver.loadtime.Aj;
import org.springframework.http.HttpHeaders;
import org.springframework.http.HttpStatus;
import org.springframework.http.ResponseEntity;
import org.springframework.http.StreamingHttpOutputMessage;
import org.springframework.security.access.prepost.PreAuthorize; import org.springframework.security.access.prepost.PreAuthorize;
import org.springframework.beans.factory.annotation.Autowired; import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.util.unit.DataUnit;
import org.springframework.web.bind.annotation.*; import org.springframework.web.bind.annotation.*;
import com.stdiet.common.annotation.Log; import com.stdiet.common.annotation.Log;
import com.stdiet.common.core.controller.BaseController; import com.stdiet.common.core.controller.BaseController;
@ -37,6 +34,7 @@ import org.springframework.web.multipart.MultipartFile;
import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse; import javax.servlet.http.HttpServletResponse;
import javax.xml.crypto.Data;
/** /**
* 客户案例管理Controller * 客户案例管理Controller
@ -127,6 +125,17 @@ public class SysCustomerCaseController extends BaseController
public TableDataInfo getFileListByCaseId(@RequestParam("caseId")Long caseId) public TableDataInfo getFileListByCaseId(@RequestParam("caseId")Long caseId)
{ {
List<SysCustomerCaseFile> list = sysCustomerCaseService.getFileListByCaseId(caseId); List<SysCustomerCaseFile> list = sysCustomerCaseService.getFileListByCaseId(caseId);
List<String> fileUrl = new ArrayList<>();
for (SysCustomerCaseFile caseFile : list) {
fileUrl.add(caseFile.getFileUrl());
}
List<String> downUrlList = AliyunOSSUtils.generatePresignedUrl(fileUrl);
if(downUrlList != null && downUrlList.size() > 0){
int index = 0;
for (String downUrl : downUrlList) {
list.get(index).setDownUrl(downUrl);
}
}
return getDataTable(list); return getDataTable(list);
} }
@ -147,7 +156,7 @@ public class SysCustomerCaseController extends BaseController
} }
FileUploadUtils.assertAllowed(file, MimeTypeUtils.DEFAULT_ALLOWED_EXTENSION); FileUploadUtils.assertAllowed(file, MimeTypeUtils.DEFAULT_ALLOWED_EXTENSION);
String fileUrl = AliyunOSSUtils.uploadFileInputSteam(AliyunOSSConfig.casePrefix, file.getOriginalFilename(), file); String fileUrl = AliyunOSSUtils.uploadFileInputSteam(AliyunOSSConfig.casePrefix, DateUtils.getDate()+"/"+file.getOriginalFilename(), file);
AjaxResult ajax = null; AjaxResult ajax = null;
if(StringUtils.isNotEmpty(fileUrl)){ if(StringUtils.isNotEmpty(fileUrl)){
@ -162,36 +171,4 @@ public class SysCustomerCaseController extends BaseController
return AjaxResult.error("文件上传失败"); return AjaxResult.error("文件上传失败");
} }
} }
/**
* 下载案例文件
* @param
* @return
*/
@PostMapping("/downCaseFile")
@PreAuthorize("@ss.hasPermi('custom:customerCase:list')")
public void downCaseFile(@RequestBody FileRequest fileRequest, HttpServletRequest request, HttpServletResponse response) {
/*try{
InputStream fileStream = AliyunOSSUtils.downloadFile(fileRequest.getFileUrl());
byte[] body = new byte[fileStream.available()];
fileStream.read(body);
HttpHeaders headers = new HttpHeaders();
headers.add("Content-Disposition", "attchement;filename=" + fileRequest.getFileName());
HttpStatus statusCode = HttpStatus.OK;
ResponseEntity<byte[]> entity = new ResponseEntity<byte[]>(body, headers, statusCode);
return entity;
}catch (Exception e) {
e.printStackTrace();
}
return null;*/
try {
response.setCharacterEncoding("utf-8");
response.setContentType("multipart/form-data");
response.setHeader("Content-Disposition",
"attachment;fileName=" + FileUtils.setFileDownloadHeader(request, fileRequest.getFileName()));
FileUtils.writeBytes(AliyunOSSUtils.downloadFile(fileRequest.getFileUrl()), response.getOutputStream());
}catch (Exception e){
e.printStackTrace();
}
}
} }

View File

@ -3,17 +3,28 @@ package com.stdiet.common.utils.oss;
import com.aliyun.oss.model.GetObjectRequest; import com.aliyun.oss.model.GetObjectRequest;
import com.aliyun.oss.model.OSSObject; import com.aliyun.oss.model.OSSObject;
import com.stdiet.common.config.AliyunOSSConfig; import com.stdiet.common.config.AliyunOSSConfig;
import com.stdiet.common.utils.file.FileUtils;
import org.springframework.web.multipart.MultipartFile; import org.springframework.web.multipart.MultipartFile;
import com.aliyun.oss.OSS; import com.aliyun.oss.OSS;
import com.aliyun.oss.OSSClientBuilder; import com.aliyun.oss.OSSClientBuilder;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.File; import java.io.File;
import java.io.FileInputStream; import java.io.FileInputStream;
import java.io.IOException; import java.io.IOException;
import java.io.InputStream; import java.io.InputStream;
import java.net.URL;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;
import java.util.UUID; import java.util.UUID;
public class AliyunOSSUtils { ; public class AliyunOSSUtils {
//下载链接默认有效期
private static final Long expire = 3600L * 1000 * 24;
public static OSS getOssClient() { public static OSS getOssClient() {
return new OSSClientBuilder().build(AliyunOSSConfig.EndPoint, AliyunOSSConfig.AccessKeyID, AliyunOSSConfig.AccessKeySecret); return new OSSClientBuilder().build(AliyunOSSConfig.EndPoint, AliyunOSSConfig.AccessKeyID, AliyunOSSConfig.AccessKeySecret);
@ -63,10 +74,10 @@ public class AliyunOSSUtils { ;
//去尾 //去尾
String tail = oranName.substring(cutPoint); String tail = oranName.substring(cutPoint);
//返回正确的带路径的图片名称 //返回正确的带路径的图片名称
return prefix + head + uuid + tail; return prefix + head + uuid + "_" + tail;
} }
//不存在 直接返回 //不存在 直接返回
return prefix + uuid + oranName; return prefix + uuid + "_" + oranName;
} }
/** /**
@ -86,8 +97,8 @@ public class AliyunOSSUtils { ;
String prefix = originalFilename.substring(0,cutPoint); String prefix = originalFilename.substring(0,cutPoint);
//获取后缀名 //获取后缀名
String suffix = originalFilename.substring(cutPoint + 1); String suffix = originalFilename.substring(cutPoint + 1);
//创建临时文件 //创建临时文件,prefix最少三位
file = File.createTempFile(prefix, suffix); file = File.createTempFile((prefix != null && prefix.length() >= 3 ? prefix : prefix+"ab"), suffix);
//multipartFile2file //multipartFile2file
multipartFile.transferTo(file); multipartFile.transferTo(file);
//删除临时文件 //删除临时文件
@ -194,7 +205,7 @@ public class AliyunOSSUtils { ;
* *
* @param fileURL 文件的url * @param fileURL 文件的url
*/ */
public static InputStream downloadFile(String fileURL) throws IOException { public static void downloadFile(String fileURL, String fileName, HttpServletRequest request, HttpServletResponse response) throws IOException {
//将url解析成objectName //将url解析成objectName
String objectName = getObjectName(fileURL); String objectName = getObjectName(fileURL);
@ -207,10 +218,57 @@ public class AliyunOSSUtils { ;
//获取流 //获取流
InputStream streamData = ossObject.getObjectContent(); InputStream streamData = ossObject.getObjectContent();
response.setCharacterEncoding("utf-8");
response.setContentType("multipart/form-data");
response.setHeader("Content-Disposition",
"attachment;fileName=" + FileUtils.setFileDownloadHeader(request, fileName));
FileUtils.writeBytes(streamData , response.getOutputStream());
// 关闭OSSClient
ossClient.shutdown();
}
/**
*
* @param fileUrl
* @return
*/
public static String generatePresignedUrl(String fileUrl){
// 创建OSSClient实例
OSS ossClient = getOssClient();
Date expiration = new Date(System.currentTimeMillis() + expire);
String url = ossClient.generatePresignedUrl(AliyunOSSConfig.Buckets, getObjectName(fileUrl), expiration).toString();
// 关闭OSSClient // 关闭OSSClient
ossClient.shutdown(); ossClient.shutdown();
return streamData; return url;
}
/**
*
* @param fileUrl
* @return
*/
public static List<String> generatePresignedUrl(List<String> fileUrlList){
List<String> downUrlList = new ArrayList<>();
// 创建OSSClient实例
OSS ossClient = getOssClient();
Date expiration = new Date(System.currentTimeMillis() + expire);
for (String fileUrl : fileUrlList) {
String url = ossClient.generatePresignedUrl(AliyunOSSConfig.Buckets, getObjectName(fileUrl), expiration).toString();
downUrlList.add(url);
}
// 关闭OSSClient
ossClient.shutdown();
return downUrlList;
} }
/** /**

View File

@ -26,6 +26,8 @@ public class SysCustomerCaseFile extends BaseEntity
@Excel(name = "文件路径") @Excel(name = "文件路径")
private String fileUrl; private String fileUrl;
private String downUrl;
/** 文件名字 */ /** 文件名字 */
@Excel(name = "文件名字") @Excel(name = "文件名字")
private String fileName; private String fileName;

View File

@ -71,12 +71,8 @@ export function uploadCseFile(data) {
} }
// 下载案例文件 // 下载案例文件
export function downCaseFile(data) { export function downCaseFile(downUrl) {
return request({ window.location.href = downUrl;
url: '/custom/customerCase/downCaseFile',
method: 'post',
data: data
})
} }

View File

@ -12,7 +12,7 @@
size="mini" size="mini"
type="text" type="text"
icon="el-icon-download" icon="el-icon-download"
@click="" @click="downloadFile(scope.row)"
>下载</el-button> >下载</el-button>
</template> </template>
</el-table-column> </el-table-column>
@ -66,7 +66,7 @@ export default {
this.fileList = []; this.fileList = [];
}, },
downloadFile(file){ downloadFile(file){
downCaseFile(file); downCaseFile(file.downUrl);
} }
}, },
}; };

View File

@ -17,7 +17,7 @@
:auto-upload="false"> :auto-upload="false">
<i class="el-icon-upload"></i> <i class="el-icon-upload"></i>
<div class="el-upload__text">将文件拖到此处<em>点击上传</em></div> <div class="el-upload__text">将文件拖到此处<em>点击上传</em></div>
<div class="el-upload__tip" slot="tip">每个案例最多上传5个文件且每个文件不超过50M</div> <div class="el-upload__tip" slot="tip">每个案例最多上传5个文件且每个文件不超过10M</div>
</el-upload> </el-upload>
</template> </template>
<script> <script>
@ -43,7 +43,7 @@ export default {
// //
limit: 5, limit: 5,
// //
fileSize: 1024 * 1024 * 50, fileSize: 1024 * 1024 * 10,
// //
multiple: true multiple: true
}, },

View File

@ -217,7 +217,8 @@
keywordArray: [ keywordArray: [
{ required: true, message: "案例关键词不能为空", trigger: "blur" }, { required: true, message: "案例关键词不能为空", trigger: "blur" },
], ],
} },
submitFlag: false
}; };
}, },
components: { components: {
@ -303,17 +304,26 @@
submitForm() { submitForm() {
this.$refs["form"].validate(valid => { this.$refs["form"].validate(valid => {
if (valid) { if (valid) {
this.form.keyword = this.form.keywordArray.join(","); if(this.submitFlag){
if (this.form.id != null) { this.$message({
updateCustomerCase(this.form).then(response => { message: "正在上传提交中,请勿重复提交",
if (response.code === 200) { type: "warning",
this.msgSuccess("修改成功"); });
this.open = false; return;
this.getList();
} }
}); this.submitFlag = true;
this.form.keyword = this.form.keywordArray.join(",");
if (this.form.id != null) {
updateCustomerCase(this.form).then(response => {
if (response.code === 200) {
this.msgSuccess("修改成功");
this.open = false;
this.getList();
}
this.submitFlag = false;
});
} else { } else {
this.$refs["uploadCaseFile"].uploadFile(); this.$refs["uploadCaseFile"].uploadFile();
} }
} }
}); });
@ -323,6 +333,7 @@
this.form.caseFileUrl = fileResult.fileUrl; this.form.caseFileUrl = fileResult.fileUrl;
if(this.form.caseFileUrl.length == 0){ if(this.form.caseFileUrl.length == 0){
this.$message.error('请至少选择一个文件上传'); this.$message.error('请至少选择一个文件上传');
this.submitFlag = false;
return; return;
} }
addCustomerCase(this.form).then(response => { addCustomerCase(this.form).then(response => {
@ -332,6 +343,7 @@
this.$refs["uploadCaseFile"].uploadReset(); this.$refs["uploadCaseFile"].uploadReset();
this.getList(); this.getList();
} }
this.submitFlag = false;
}); });
}, },
selectCustomer(){ selectCustomer(){