这是用于返回xdocument文件的控制器代码。我将其转换为memorystream,然后将其作为base64字符串返回。
[HttpPost]
public ActionResult ImportAcesFileAjax(TransactionViewModel transactionViewModel)
{
XDocument xDocument = new XDocument();
try
{
if (transactionViewModel.File.IsNotNullObject())
{
ImportService importService = new ImportService();
xDocument = importService.ProcessExcelFileForTransformation(transactionViewModel);
_logger.Information($"Finished processing {transactionViewModel.File.FileName}");
}
}
catch (Exception e)
{
_logger.Error($"Error: {e.Message}");
_logger.Error(e.StackTrace);
throw;
}
return ReturnImportXmlAsByte(xDocument, "import.xml");
}
protected ActionResult ReturnImportXmlAsByte(XDocument xDocument, string xmlFilename)
{
using (MemoryStream stream = new MemoryStream())
using(XmlWriter xmlWriter = XmlWriter.Create(stream))
{
xDocument.WriteTo(xmlWriter);
var byteLength = stream.ToArray().Length;
var base64String = Convert.ToBase64String(stream.ToArray(), 0, byteLength);
return Json(new {base64String = base64String, xmlFilename = xmlFilename});
}
}
我在前端使用以下代码:
$.ajax({
url: requestUrl,
type: "POST",
data: formData,
contentType: false,
processData: false,
success: function (excelByteResult) {
var bytes = base64ToBytes(excelByteResult.base64String);
var blob = new Blob([bytes], { type: "text/xml" });
const url = window.URL.createObjectURL(blob);
const a = document.createElement('a');
a.style.display = 'none';
a.href = url;
a.download = excelByteResult.xmlFilename;
document.body.appendChild(a);
a.click();
window.URL.revokeObjectURL(url);
},
error: function (jqXHR, textStatus, errorThrown) {
console.log("Xhr: " + jqXHR.responseText);
console.log("Status: " + status);
console.log("Error Thrown: " + errorThrown);
}
});
ajax调用成功,但我似乎无法访问该文件。除了我的方法,我们还有其他可行的方法吗?要求是通过ajax下载xml文件
暂无答案!
目前还没有任何答案,快来回答吧!