在浏览器中下载Javascript文档.Web API
Javascript download document in browser. Web API
我使用Web API来获取我的文档,使用如下:
[Route("Api/DocumentApi/DownloadDocument")]
[HttpGet]
public IHttpActionResult DownloadDocument(int documentID)
{
Document documentToDownload = new Document();
using (TrustInvestmentSwitchEntities db = new TrustInvestmentSwitchEntities())
{
DocumentRepository repo = new DocumentRepository();
documentToDownload = repo.GetSingle(db, x => x.ID == documentID);
}
var stream = new MemoryStream();
var result = new HttpResponseMessage(HttpStatusCode.OK)
{
Content = new ByteArrayContent(stream.GetBuffer())
};
result.Content.Headers.ContentDisposition = new System.Net.Http.Headers.ContentDispositionHeaderValue("attachment")
{
FileName = documentToDownload.FileName
};
result.Content.Headers.ContentType = new MediaTypeHeaderValue("application/octet-stream");
var response = ResponseMessage(result);
return response;
}
这看起来像是在检索文档。但是,我希望文档要么立即下载,要么显示一个弹出窗口,让用户选择保存文件的位置,而这并没有发生。建议立即下载
这是我的Javascript GET,我认为这是问题:
DocumentToDownload = $(that).closest('.document-item').data('documentid');
var url = '/Api/DocumentApi/DownloadDocument';
var data = {
DocumentID: DocumentToDownload
};
$.ajax({
type: "GET",
url: url,
contentType: "application/json",
data: data,
dataType: "json",
success: function (json, status) {
if (status != "success") {
log("Error loading data");
return;
}
log("Data loaded!");
},
error: function (result, status, err) {
log("Error loading data");
return;
}
});
我不知道后面该放什么:
success: function (json, status) {
出于安全原因,不允许下载Ajax文件(否则任何站点都可以在后台将任何文件下载到用户的机器上)
不需要使用ajax调用,如果href
指向一个返回文档(头是文档)的URL,您可以触发下载,而无需使用正常链接重新加载页面,这看起来像您的API正在做的。所以你可以简单地输入:
<a href="/Api/DocumentApi/DownloadDocument?DocumentID=10">Download</a>
其中documententid设置为要下载的文档的ID。当用户点击链接时,页面不会改变/刷新
相关文章:
- 使用promise和mongoose对文档进行排序
- document.open/document.write没有正确地清除chrome中的文档——这是chrome的错误吗
- Ajax请求文档就绪会导致jquery加载缓慢
- MongoDB (php) - 以数组而不是多个属性的形式返回文档属性
- 谷歌文档表面引擎
- 将文档上载到Web API
- 使用 HTML5 和 ASP .NET MVC 后端的 Web 浏览器中的标记工具实时共享文档预览
- 在 Web 视图中设置 innerHTML 将替换整个文档,而不仅仅是元素
- Web浏览器控件:如何捕获文档事件
- Web浏览器用于注释文档的文本注释器
- 如何为我的web应用程序创建文档预览/视图(类似于Dropbox)
- 限制web表单中文件上传框的文档类型
- 有关于Tizen Web应用程序模板的文档吗?(如媒体控制器,相机,计步器)
- 基于web的PDF文档编辑器
- 通过Web lotus domino打印视图中的多个选定文档
- “内容width"web文档的
- 在浏览器中下载Javascript文档.Web API
- 从servlet向web文档发送一个图像URL
- 使用 Web 浏览器打印文档显示
- 在Meteor web应用程序中显示多维数据库文档