【发布时间】:2017-10-24 13:41:11
【问题描述】:
我想从 Ajax 响应中打开文件。这是代码。这里的 Ajax 调用响应包含 PDF 文件。
我想在浏览器的新标签页中打开文件。这里我使用的是 mvc 框架。
function ViewPDF(key){
$.ajax({
url: '@Url.Action("OpenDocument", "DocumentApproveUser")',
type: "POST",
data: { "key": key},
async: true,
cache: false,
success: function (data, status, xhr) {
alert(data);
window.open(data);
if (xhr.getResponseHeader("Forcefullylogin") == "true") {
var url = "/Login/Login";
window.location.href = url;
}
else {
}
},
error: function (error) {
$("#divLoading").hide();
if (error.getResponseHeader("Forcefullylogin") == true") {
var url = '@Url.Action("Login", "Login")';
window.location.href = url;
}
else {
alert('Something went wrong in system.Please try again later!or contact to system administrator.');
}
}
});
}
服务器代码: 下面是我的控制器的代码。此代码将 pdf 文件作为 ajax 响应返回。 我想在我的浏览器中打开该响应。
[HttpPost]
public ActionResult OpenDocument(string key)
{
try
{
int Id = 0;
try
{
byte[] data = Convert.FromBase64String(key);
string decodedString = System.Text.Encoding.UTF8.GetString(data);
if (!(String.IsNullOrEmpty(decodedString)))
Id = Convert.ToInt32(decodedString);
}
catch (Exception ex)
{
ViewBag.ErrorName = "An error occured while opening document.";
base.ErrorLogger.Error("***OpenDocument***", ex);
return null;
}
DocumentApproveViewModel vm = new DocumentApproveViewModel();
vm.DocumentsApprovalModel = DocumentApproveViewModel.GetDocTransactionModelList(_repo.GetAll());
DocumentApprovalModel lst;
lst = (from x in vm.DocumentsApprovalModel where x.Id.Equals(Id) select x).FirstOrDefault();
base.Logger.InfoFormat("User : '{0}' going to access pdf document at {1} ", SessionFactory.CurrentUser.Name, System.DateTime.Now);
/////////////////////////////////////////////////////////////////////
ICollection<PasswordManagementViewModel> passwordList = null;
PasswordManagementViewModel password = null;
passwordList = PasswordManagementViewModel.GetSystemEncryptionKeyList(_encryption.GetAll());
password = passwordList.OrderByDescending(x => x.CreatedDateTime).FirstOrDefault();
string decryptPassword = Base64EncodeDecode.Decrypt(password.EncryptionKey, true);
/////////////////////////////////////////////////////////////////////
// Inhariting Logic from PDFSharpUtil Class.
byte[] PdfFileByte = _docSecurity.OpenPdfFile(lst.File, decryptPassword, SessionFactory.CurrentUser.EncryptionKey, SessionFactory.CurrentUser.Name, lst.DocumentTransactionName, false, SessionFactory.PdfViewCount);
/// Added logic for adding data into Document History ///
DocumentHistory objDocumentHistory = new DocumentHistory();
objDocumentHistory.SentTo = null;
objDocumentHistory.Timestamp = DateTime.UtcNow;
objDocumentHistory.ActionPerformedBy = SessionFactory.CurrentUser.Id;
objDocumentHistory.Action = EDocumentAction.View;
objDocumentHistory.DocumentId = Id;
_docHistoryRepo.Add(objDocumentHistory);
//Increment view count not to ask password from second attempt to open PDF file
SessionFactory.PdfViewCount++;
return File(PdfFileByte, "application/pdf");
}
catch (Exception ex)
{
ViewBag.ErrorName = "An error occured while opening Document";
base.ErrorLogger.Error("***OpenDocument :: DocumentView***", ex);
}
return null;
}
【问题讨论】:
-
你也可以分享服务器代码吗?你得到什么错误?
-
OpenDocument方法返回什么?你为什么要打ajax电话?如果您知道客户端文件的 url,只需使用window.location.herf=thatUrl; -
见上文我也共享了服务器端代码。
-
您的代码是否询问用户是否要保存文件(或者,根据浏览器设置,自动将其保存到下载文件夹中)?我不认为 ajax 是这样做的正确方法。只需打开一个直接调用 OpenDocument 方法的新窗口(通过 GET,您需要启用该方法),然后它将显示文件,假设用户在其浏览器中安装了 PDF 查看器。
标签: c# jquery ajax model-view-controller