1.報(bào)錯(cuò)如圖
2.項(xiàng)目背景
我們的項(xiàng)目采用的全是https請(qǐng)求,而使用第三方文件管理器go-fastdfs,該文件管理器返回的所有下載文件的請(qǐng)求全是http開頭的,比如http://10.110.38.253:11014/group1/batchImportData/組 (26).xlsx,然而在https請(qǐng)求下使用http的請(qǐng)求就會(huì)報(bào)如上圖的錯(cuò)誤,且不能把文件下載請(qǐng)求http改為https,因?yàn)樾薷暮髸?huì)查詢不到文件。所以必須只能采用http的請(qǐng)求且想讓功能實(shí)現(xiàn)。
注意點(diǎn)1:
我們公司項(xiàng)目請(qǐng)求協(xié)議前綴必須是https的,執(zhí)行http的無(wú)效
注意點(diǎn)2:
這種第三方返回的文件下載路徑http://10.110.38.253:11014/group1/batchImportData/組 (26).xlsx,是可以直接放在瀏覽器上直接下載的,具體請(qǐng)看如圖
3.網(wǎng)上的解決方案
可以先看下其他人的博客,但是方案對(duì)我目前公司項(xiàng)目無(wú)效
1.https頁(yè)面加載http資源的解決方法
2.分享 4個(gè)解決 https頁(yè)面加載http資源報(bào)錯(cuò)的方法
問(wèn)題:里面的方案為啥對(duì)我公司的項(xiàng)目無(wú)效?
答案:
- 針對(duì)修改協(xié)議前綴的方案,我們的必須得是https的才行,其他無(wú)效。
- 針對(duì)使用 iframe 的方案,因?yàn)闆](méi)用過(guò),且感覺項(xiàng)目引入會(huì)很費(fèi)事且龐雜,所以當(dāng)時(shí)沒(méi)考慮該方案。
- 針對(duì)自動(dòng)升級(jí)方案(也就是說(shuō)把第三方文件管理器go-fastdfs配置文件改了,由http協(xié)議改為https協(xié)議),該方案真對(duì)我的項(xiàng)目不行,因?yàn)槲业墓居泻芏嗬享?xiàng)目都是用這個(gè)文件管理器go-fastdfs,如果把協(xié)議改了,不清楚對(duì)其他服務(wù)會(huì)不會(huì)有影響,所以輕易不能動(dòng)。
綜上所述:
上面的方案我一個(gè)都不能用,所以我需要另想他法。
4.我的最終解決方案
接下來(lái)說(shuō)下我最終想到的方便且容易上手的解決方案:那就是采用http工具執(zhí)行url -> 然后把文件先下載到項(xiàng)目所在服務(wù)器的臨時(shí)目錄內(nèi) -> 然后再以讀取普通文件路徑的方式加載成File -> 再然后以流的方式輸出給客戶端彈窗另存為保存 -> 最后關(guān)閉流并刪除服務(wù)器路徑下的臨時(shí)文件。
pom.xml
<dependency>
<groupId>org.apache.poi</groupId>
<artifactId>poi-ooxml</artifactId>
<version>3.17</version>
</dependency>
<dependency>
<groupId>org.apache.httpcomponents</groupId>
<artifactId>httpclient</artifactId>
<version>4.4.1</version>
</dependency>
<dependency>
<groupId>cn.hutool</groupId>
<artifactId>hutool-all</artifactId>
<version>5.7.17</version>
</dependency>
前端js代碼
//批量管理-下載批量導(dǎo)入數(shù)據(jù)
function downloadBatchImportDataTaskActionColumn(taskId) {
var language = 'zh';
if(Cookies.get("language") != null && Cookies.get("language") != "")
{
language = Cookies.get("language") ;
}
var url = prefix + "/downloadBatchImportData?language=" + language;
var form = $("<form></form>").attr("action", url).attr("method", "post");
form.append($("<input></input>").attr("type", "hidden").attr("name", "taskId").attr("value", taskId));
form.appendTo('body').submit().remove();
}
后端Controller代碼
/**
* 下載批量導(dǎo)入數(shù)據(jù)
* 流程:
* 查詢數(shù)據(jù)庫(kù)判斷filedownLink字段是否為空
* 為空:則代表舊數(shù)據(jù),沒(méi)有g(shù)ofd對(duì)應(yīng)的下載文件地址,因此把模板文件返回給客戶端
* 不為空:則代表gofd已經(jīng)上傳了對(duì)應(yīng)的批量導(dǎo)入文件,且數(shù)據(jù)庫(kù)中保存地址鏈接
* 通過(guò)filedownLink封裝成FiLE
* 判斷File在臨時(shí)目錄內(nèi)是否存在
* 存在:則直接返回給客戶端,最后再把服務(wù)器臨時(shí)目錄內(nèi)文件刪除
* 不存在:則通過(guò)http工具調(diào)用filedownLink封裝成File,將文件寫入tempFilePath臨時(shí)目錄內(nèi),再把文件File返回給客戶端,最后再把服務(wù)器臨時(shí)目錄內(nèi)文件刪除
* @param req req
* @param response response
*/
@RequestMapping(value = "/downloadBatchImportData")
public void downloadBatchImportData(HttpServletRequest req, HttpServletResponse response) {
logger.info("-downloadBatchImportData-begin");
String taskId = req.getParameter("taskId");
OutputStream os = null;
InputStream io = null;
String tempFilePath = TEMP_FILE_PATH;
String fileName = "";
String language = req.getParameter("language");
Workbook wb = null;
try {
ImpExpTaskDetail impExpTaskDetail = isvcBatchTaskServiceMicro.selectTaskDetailByTaskId(taskId);
String filedownLink = impExpTaskDetail.getLink();
if (org.springframework.util.StringUtils.isEmpty(filedownLink)) {
fileName = MessageUtils.message("batch.template") + ".xlsx";
String templateFileName = BatchConstant.DOWNAD_TEMPLATE_NAME + "_" + language + BatchConstant.EXTENSION_XLSX;
SysUser sysUser = ShiroUtils.getSysUser();
logger.info("-downloadBatchImportData-taskId:{},language:{}", taskId, language);
if (isysUserService.get36kType(sysUser.getUserId()) == Poc36kEnum.POC6K.getType()) {
templateFileName = BatchConstant.DOWNAD_TEMPLATE_NAME + "6k" + "_" + language + BatchConstant.EXTENSION_XLSX;
}
File templateFile = org.springframework.util.ResourceUtils.getFile("classpath:" + templateFileName);
logger.info("-Template file exist!,templateFileName:{}", templateFileName);
io = new FileInputStream(templateFile);
wb = new XSSFWorkbook(io);
} else {
fileName = StringUtils.subscribeNameString(filedownLink);
File file = ResourceUtils.getFile(String.join(File.separator, tempFilePath, fileName));
if (!file.exists()) {
String begin = DateUtil.now();
DateTime beginTime = DateUtil.parse(begin);
long download = HttpUtil.downloadFile(filedownLink, FileUtil.file(tempFilePath, fileName), new StreamProgress() {
@Override
public void start() {
logger.info("開始下載,時(shí)間為:" + begin);
}
@Override
public void progress(long progressSize) {
logger.info("已下載:{}", FileUtil.readableFileSize(progressSize));
}
@Override
public void finish() {
String end = DateUtil.now();
DateTime endTime = DateUtil.parse(end);
long between = DateUtil.between(beginTime, endTime, DateUnit.MS);
logger.info("下載完成,用時(shí):" + DateUtil.formatBetween(between, BetweenFormatter.Level.SECOND));
}
});
}
io = new FileInputStream(file);
wb = new XSSFWorkbook(io);
}
logger.info("-tempFilePath:{},fileName:{}", tempFilePath, fileName);
response.setContentType("application/octet-stream;charset=UTF-8");
response.setHeader("Content-disposition", "attachment; filename=" + URLEncoder.encode(fileName, StandardCharsets.UTF_8));
wb.write(response.getOutputStream());
} catch (IOException e) {
logger.error("-downloadBatchImportData error:{}", e.getMessage());
} finally {
if (os != null) {
try {
os.close();
} catch (IOException e) {
logger.error("-OutputStream error:{}", e.getMessage());
}
}
if (io != null) {
try {
io.close();
} catch (IOException e) {
logger.error("-InputStream error:{}", e.getMessage());
}
}
if (Optional.ofNullable(tempFilePath).isPresent()) {
// 強(qiáng)制刪除臨時(shí)文件
boolean isDelete = com.hytalk.util.FileUtil.delFile(new File(tempFilePath));
logger.info("-downloadBatchImportData 強(qiáng)制刪除臨時(shí)文件 , filePath: {} , isDelete : {} ", tempFilePath, isDelete);
}
}
}
FileUtil工具類
import java.io.File;
/**
* 文件工具
* @Author 211145187
* @Date 2023/4/19 14:27
**/
public class FileUtil {
/**
* 刪除文件
* @param file 文件
* @return boolean
*/
public static boolean delFile(File file) {
if (!file.exists()) {
return false;
}
if (file.isDirectory()) {
File[] files = file.listFiles();
for (File f : files) {
delFile(f);
}
}
return file.delete();
}
}
StringUtils工具類
/**
* 字符串工具
* @author 211145187
* @Date: 2021/11/11 16:11
**/
public class StringUtils {
/**
* 截取url地址中的名稱,比如路徑地址為“http://10.110.38.253:11014/group1/batchImportData/組 (26).xlsx”,最后截取的名稱為“組 (26).xlsx”
* @param str 原字符串
* @return 截取后的字符串
*/
public static String subscribeNameString(String str) {
if (str.lastIndexOf("/") > -1) {
str = str.substring(str.lastIndexOf("/") + 1);
}
return str;
}
}
說(shuō)明:文章來(lái)源:http://www.zghlxwxcb.cn/news/detail-549196.html
只在意我的思路流程即可,至于工具類或者查數(shù)據(jù)庫(kù)數(shù)據(jù)代碼啥的就不復(fù)制粘貼了。文章來(lái)源地址http://www.zghlxwxcb.cn/news/detail-549196.html
到了這里,關(guān)于https頁(yè)面加載http資源的解決方法的文章就介紹完了。如果您還想了解更多內(nèi)容,請(qǐng)?jiān)谟疑辖撬阉鱐OY模板網(wǎng)以前的文章或繼續(xù)瀏覽下面的相關(guān)文章,希望大家以后多多支持TOY模板網(wǎng)!