Joe*_*ter 20 javascript android angularjs cordova ionic-framework
我在我当前的项目中使用Anuglar,Ionic和Cordova,我正在尝试将包含图像文件的FormData发布到我的服务器.现在我正在使用cordova相机插件将文件路径返回到设备上的图像(例如:file:// path/to/img).一旦我有了文件路径,我想使用images文件路径将图像文件附加到FormData对象.这是我现在的代码.
var fd = new FormData();
fd.append('attachment', file);
fd.append('uuid', uuid);
fd.append('userRoleId', userRole);
Run Code Online (Sandbox Code Playgroud)
上面的代码在附加从文件中获取的文件时起作用,<input type='file'>
但在给定设备上的文件路径时不起作用.
基本上FormData现在显示如下:
------WebKitFormBoundaryasdf
Content-Disposition: form-data; name="attachment";
file://path/to/img
Run Code Online (Sandbox Code Playgroud)
我希望它看起来像这样
------WebKitFormBoundaryasdf
Content-Disposition: form-data; name="attachment"; filename="jesus-quintana.jpg"
Content-Type: image/jpeg
Run Code Online (Sandbox Code Playgroud)
我找到了许多不同的方法来使用cordova FileTransfer上传图像,并将图像转换为base64然后上传它.但我找不到任何简单的方法来通过使用路径并在表单中发布它来抓取文件.我对File Api不是很熟悉,所以任何帮助都会受到赞赏
Joe*_*ter 40
经过一番摆弄,我设法找到一个非常简单的解决方案.首先我添加了cordova文件插件然后我使用下面的代码
var fd = new FormData();
window.resolveLocalFileSystemURL(attachment.img, function(fileEntry) {
fileEntry.file(function(file) {
var reader = new FileReader();
reader.onloadend = function(e) {
var imgBlob = new Blob([ this.result ], { type: "image/jpeg" } );
fd.append('attachment', imgBlob);
fd.append('uuid', attachment.uuid);
fd.append('userRoleId', 12345);
console.log(fd);
//post form call here
};
reader.readAsArrayBuffer(file);
}, function(e){$scope.errorHandler(e)});
}, function(e){$scope.errorHandler(e)});
Run Code Online (Sandbox Code Playgroud)
所以我只是创建一个表单并使用FileReader将ArrayBuffer插入Blob对象,然后将其附加到表单数据.希望这有助于其他人寻找一种简单的方法来做到这一点.
您确实需要发送文件内容.使用HTML5 FileAPI,您需要创建FileReader对象.
前段时间,我用cordova开发了一个应用程序,我不得不阅读一些文件,然后我创建了一个名为CoFS的库(首先是Cordova FileSystem,但它在某些浏览器中有效).
它处于测试状态,但我使用它并且效果很好.您可以尝试这样做:
var errHandler = function (err) {
console.log("Error getting picture.", err);
};
var sendPicture = function (file) {
var fs = new CoFS();
fs.readFile(file, function (err, data) {
if (err) {
return errHandler(err);
}
var fd = new FormData();
fd.append('attachment', new Blob(data));
fd.append('uuid', uuid);
fd.append('userRoleId', userRole);
console.log("Data of file:" + data.toString('base64'));
// Send fd...
});
};
navigator.camera.getPicture(sendPicture, errHandler);
Run Code Online (Sandbox Code Playgroud)
抱歉,我的英语很差.
归档时间: |
|
查看次数: |
19009 次 |
最近记录: |