背景:用户有一个excel导入数据,如果有报错或者其他消息需要返回前台一个有这些信息的excel文件的需求。
问题:许久没用过表单就用的ajax,发现能把excel文件以multipart request的方式传到后端controller层处理,但是返回不了前台。后续看了许多文章,才得知ajax的返回值只能是字符流,而导出excel是后台往浏览器中写入二进制的字节流,所以才有下面这种情况,后面用表单进行处理后就可以了。
参考前端js表单提交(上传按钮的点击事件):
var exportForm = document.forms["ExportForm"];
// 页面中放置一个隐藏的iframe 处理Form提交结果
var exportIframe = document.getElementById("ExportFrame");
if (isAvailable(exportForm)) {
document.body.removeChild(exportForm); // 清除已有的form表单
}
if (isAvailable(exportIframe)) {
document.body.removeChild(exportIframe); // 移除iframe
}
exportIframe = document.createElement("iframe");
exportIframe.setAttribute("id", "ExportFrame");
exportIframe.setAttribute("name", "ExportFrame");
exportIframe.style.display = 'none';
document.body.appendChild(exportIframe);
exportForm = document.createElement("form");
exportForm.setAttribute("id", "ExportForm");
exportForm.setAttribute("method", "POST");
// exportForm.setAttribute("target", "_blank");
exportForm.setAttribute("target", "ExportFrame");
exportForm.setAttribute("action", "localhost:8080/web/export1");
exportForm.setAttribute("enctype", "multipart/form-data");
var inputField = document.createElement("input");
inputField.setAttribute("type", "file");
inputField.setAttribute("name", "file");
inputField.setAttribute("value", $("#articleImageFile")[0].files[0]);
exportForm.appendChild(inputField);
var inputField = document.createElement("input");
inputField.setAttribute("type", "hidden");
inputField.setAttribute("name", "name");
inputField.setAttribute("value", "测试哟");
exportForm.appendChild(inputField);
document.body.appendChild(exportForm);
exportForm.submit();
相关参考文章链接:
前端:ajax调用导出数据到excel方法,方法有执行但没有下载_乐事原味~的博客-CSDN博客