Cordova/phonegap:具有文件传输插件的FileTransferError.FILE_NOT_FOUND_ERR [英] Cordova/phonegap: FileTransferError.FILE_NOT_FOUND_ERR with file transfer plugin
问题描述
在我的phonegap应用中,我用相机拍摄了一张照片,该照片可以正常工作.
In my phonegap app I take a picture with my camera and it works as expected.
然后,我想将其发送到我的服务器.我发现发送base64编码的字符串是一种不好的做法,我发现最好的解决方案是使用文件传输插件.
Then, I'd like to send it to my server. I see that sending the base64 encoded string is a bad practice and I figured the best solution is using the file transfer plugin.
因此,我添加了插件,并编写了以下代码:
So, I added the plugin and I wrote this:
function onPhotoURISuccess(imageURI) {
try{
var url = "myserver/addPhoto";
alert(url);
var options = new FileUploadOptions();
options.chunkedMode = false;
options.fileKey = "recFile";
var imagefilename = imageURI;
options.fileName = imagefilename;
options.mimeType = "image/jpeg";
options.params = { "token": APP.TOKEN};
var ft = new FileTransfer();
alert(imagefilename);
ft.upload(imageURI, url, win, fail, options);
}
catch (err) {
alert(err.message);
}
}
在try分支的最后一行,出现错误 FileTransferError.FILE_NOT_FOUND_ERR .
In the last line in the try branch, I get the error FileTransferError.FILE_NOT_FOUND_ERR.
在此行之前的警报中,我在警报中显示路径( imagefilename 变量).如果我尝试在Android设备中的该路径上手动进行操作,则找不到它.路径为 file:///storage/emulated/0/Android/data/com.My.App/cache/1505307795417.jpg
In the alert before this line, I show in the alert the path (imagefilename variable). If I try to go manually in that path in my Android device, I can't find it. The path is file:///storage/emulated/0/Android/data/com.My.App/cache/1505307795417.jpg
所以,我试图设置该选项
So, I tried to set the option
saveToPhotoAlbum: true
检查图像是否已保存,并且我可以正确查看相册中的照片.我不知道为什么在发送错误时会收到错误消息,这可能是路径错误吗?
to check if the image is saved and I correctly see the photo in my album. I don't know why I get the error while sending it, can be the path wrong?
我不认为问题出在服务器端,因为我什至看不到服务器日志中的请求.
I don't think the problem is server side, since I can't even see the request in the server log.
更新:
在Anuj T建议之后,我也尝试了此操作,但结果仍然相同:
I also tried this after Anuj T suggestion, but the result is still the same:
function onPhotoURISuccess(imageURI) {
var filepath;
window.resolveLocalFileSystemURL(imageURI, function success(fileEntry) {
// Do something with the FileEntry object, like write to it, upload it, etc.
// writeFile(fileEntry, imageURI);
filepath = fileEntry.fullPath;
alert("got file: " + fileEntry.fullPath);
// displayFileData(fileEntry.nativeURL, "Native URL");
try {
var url = "myUrl";
alert(url);
var options = new FileUploadOptions();
options.chunkedMode = false;
options.fileKey = "recFile";
var imagefilename = filepath;
options.fileName = imagefilename;
options.mimeType = "image/jpeg";
options.params = { "token": APP.TOKEN }; // if we need to send parameters to the server request
var ft = new FileTransfer();
alert(imagefilename);
alert(imageURI);
ft.upload(filepath, url, win, fail, options);
}
catch (err) {
alert(err.message);
}
}, function () {
// If don't get the FileEntry (which may happen when testing
// on some emulators), copy to a new FileEntry.
alert("file system fail");
createNewFileEntry(imgUri);
});
}
更新2:
这是我的服务器端代码.
This is my server side code.
internal GenericResponse AddChiusuraPhoto(string token)
{
Utility.Logger("AddChiusuraPhoto");
var gr = new GenericResponse();
if (CheckToken(token, out IS_UTENZE utente))
{
try
{
var md5 = new md5Manager();
HttpPostedFile file = HttpContext.Current.Request.Files["recFile"];
if (file == null)
return null;
string targetFilePath = @"C:\ProgramData\" + file.FileName;
file.SaveAs(targetFilePath);
Utility.Logger("[AddChiusuraPhoto] Returning lista ");
return gr;
}
catch (Exception ex)
{
gr.ESITO = "[KO]";
gr.MESSAGGIO = ex.ToSafeString();
Utility.Logger("AddChiusuraPhoto " + gr.MESSAGGIO);
}
}
else
{
gr.ESITO = "[KO]";
gr.MESSAGGIO = "Utente non loggato, impossibile effettuare il logout.";
Utility.Logger("AddChiusuraPhoto " + gr.MESSAGGIO);
}
return gr;
}
请注意,这是WCF.这是地址部分:
Note that this is a WCF. This is the addressing part:
[OperationContract]
[WebInvoke(UriTemplate = "chiusure/addPhoto", Method = "POST", BodyStyle = WebMessageBodyStyle.Wrapped, RequestFormat = WebMessageFormat.Json, ResponseFormat = WebMessageFormat.Json)]
GenericResponse AddChiusuraPhoto(string token);
推荐答案
您需要拍照并获取FileEntry对象
如果需要使用FileEntry对象,请在CameraOptions对象中将destinationType设置为 Camera.DestinationType.FILE_URI .
If you need to use a FileEntry object, set the destinationType to Camera.DestinationType.FILE_URI in your CameraOptions object
更新后的代码
function getPicture(){
var srcType = Camera.PictureSourceType.CAMERA;
var options = setOptions(srcType);
//var func = createNewFileEntry;
navigator.camera.getPicture(function cameraSuccess(imageUri) {
//displayImage(imageUri);
// You may choose to copy the picture, save it somewhere, or upload.
//func(imageUri);
var filename = imageUri.substr(imageUri.lastIndexOf('/') + 1);
window.resolveLocalFileSystemURL(cordova.file.cacheDirectory, function success(dirEntry) {
// Do something with the FileEntry object, like write to it, upload it, etc.
// writeFile(fileEntry, imgUri);
console.log("got file: " + dirEntry.fullPath);
console.log("file name " + filename);
// JPEG file
dirEntry.getFile(filename, { create: true, exclusive: false }, function (fileEntry) {
// Do something with it, like write to it, upload it, etc.
// writeFile(fileEntry, imgUri);
console.log("got file: " + fileEntry.fullPath);
// displayFileData(fileEntry.fullPath, "File copied to");
upload(fileEntry);
}, onErrorCreateFile);
// displayFileData(fileEntry.nativeURL, "Native URL");
}, function () {
// If don't get the FileEntry (which may happen when testing
// on some emulators), copy to a new FileEntry.
//createNewFileEntry(imgUri);
});
//console.log(imageUri);
}, function cameraError(error) {
console.debug("Unable to obtain picture: " + error, "app");
}, options);
};
设置选项功能.
function setOptions(srcType) {
var options = {
// Some common settings are 20, 50, and 100
quality: 50,
destinationType: Camera.DestinationType.NATIVE_URI ,
// In this app, dynamically set the picture source, Camera or photo gallery
sourceType: srcType,
encodingType: Camera.EncodingType.JPEG,
mediaType: Camera.MediaType.PICTURE,
allowEdit: false,
saveToPhotoAlbum:false,
correctOrientation: true //Corrects Android orientation quirks
};
return options;
}
请参阅详细说明 要将文件上传到服务器
function upload(fileEntry) {
var fileURL = fileEntry.toURL();
var success = function (r) {
console.log("Successful upload..." + JSON.stringify(r));
console.log("Code = " + JSON.stringify(r.responseCode));
alert(JSON.stringify(r.response));
// displayFileData(fileEntry.fullPath + " (content uploaded to server)");
};
var fail = function (error) {
alert("An error has occurred: Code = " + error.code);
console.log("Error= " + error);
};
var options = new FileUploadOptions();
options.fileKey = "file";
options.fileName = fileURL.substr(fileURL.lastIndexOf('/') + 1);
options.mimeType = "text/plain";
var params = {};
params.value1 = "test";
params.value2 = "param";
options.params = params;
var SERVER = "http://posttestserver.com/post.php";
var ft = new FileTransfer();
// SERVER must be a URL that can handle the request, like
// http://some.server.com/upload.php
ft.upload(fileURL, encodeURI(SERVER), success, fail, options);
}
收到成功警报后,您还可以检查是否将参数上传到服务器,您将成功收到链接.
when you get the success alert you can also check your params uploaded to the server or not, you will receive the link in success.
希望获得帮助.
这篇关于Cordova/phonegap:具有文件传输插件的FileTransferError.FILE_NOT_FOUND_ERR的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!