【发布时间】:2015-09-17 21:46:42
【问题描述】:
我正在开发一个 Phonegap/Cordova 应用程序,我能够使用 FileTransfer 插件下载一个文件并将其放入手机的根文件夹中。该文件是托管在服务器上的简单图像。
但是,我正在尝试下载由我的 API 生成的文件(文件未托管在服务器上)。一旦你点击 api,它就会返回一个二进制文件流。此代码在浏览器中使用 AJAX 时运行良好,但在我的 Android 手机(测试)上不起作用。当我这样做时,我得到错误代码 1。
如果我的 URI 是托管在实际服务器上的文件,我的 fileTransfer.download 运行良好。
我返回文件的 API 是这种格式:
http://api.mydomainname.com/file/23
其中 23 是文件 ID。
这是我的代码:
document.addEventListener("deviceready", onDeviceReady, true);
var store;
var assetURL = encodeURI("http://api.mydomainname.com/file/23");
var fileName = "test.xlsx";
function onDeviceReady() {
window.requestFileSystem(LocalFileSystem.PERSISTENT, 0, gotSys, fail);
}
function gotSys(fileSystem) {
alert("Got FS");
store = fileSystem.root;
alert('Checking file: ' + store.toURL() + fileName);
window.resolveLocalFileSystemURL(store.toURL() + fileName, appStart, downloadAsset);
}
function downloadAsset() {
var fileTransfer = new FileTransfer();
alert("About to start transfer");
fileTransfer.download(assetURL, store.toURL() + fileName,
function (entry) {
alert("Success!");
},
function (err) {
alert("Download error : " + err.code);
});
}
function appStart() {
alert('file exists');
alert(store.toURL() + fileName);
}
function fail(error) {
alert("fail error: " + error);
}
我尝试过的 C# 返回(尝试之一)是:
response = new HttpResponseMessage(HttpStatusCode.OK);
response.Content = new StreamContent(new MemoryStream(docData));
response.Content.Headers.ContentDisposition = new System.Net.Http.Headers.ContentDispositionHeaderValue("attachment");
response.Content.Headers.Add("Content-Type", "application/octet-stream");
response.Content.Headers.ContentDisposition.FileName = doc.DocumentName;
return response;
我尝试返回二进制、json(带有文件二进制内容)等。有什么建议吗?甚至可以下载不在服务器上的文件吗?
谢谢
【问题讨论】: