嗨,我想拍照并上传到我的服务器。这是我在下面的nativescript代码
一旦我运行我的应用程序并拍照将其发送到服务器。服务器返回一个错误消息,就像这个一样
注意:这是我用于nativescript应用程序的标头
var headers = {"Content-Type": "multipart/form-data"}
另外在nativescript中是否有文件系统模块的createReadStream()方法?
你可以使用nativescript-background-http
插件。这是你如何使用它
var bghttp = require("nativescript-background-http");
var session = bghttp.session("image-upload");
// save the image somewhere
var folder = fs.knownFolders.documents();
var pathOfImage = fs.path.join(folder.path, "Test.png");
var saved = image.saveToFile(pathOfImage,".png");
var request =
url : uploadPhotoUrl,
method : "POST",
headers : {
"Content-Type" : "application/octet-stream"
}
};
var task = session.uploadFile(pathOfImage,request);
编辑
在后端(nodejs + express),您可以实现中间件功能并使用:
var rawParser = bodyParser.raw({
type: 'application/octet-stream', extended: true
});
app.post("/photoUpload",rawParser,function(req,res){
var path = "uploads/test.jpg";
var file = fs.writeFileSync(path,req.body);
});
以下是文件上传到QuickBlox的示例(它支持AWS S3,支持“multipart / form-data”)
var fs = require("tns-core-modules/file-system");
var imagepicker = require("nativescript-imagepicker");
var bghttp = require("nativescript-background-http");
var parseUri = require("parseUri");
var ile = fs.File.fromPath(this.filePath);
var size = file.readSync().length;
var contentType = 'image/jpeg';
var uri = parseUri(createResult.blob_object_access.params),
uploadUrl = uri.protocol + "://" + uri.authority + uri.path;
var uploadParams = [];
Object.keys(uri.queryKey).forEach(function(val) {
uploadParams.push({name: val, value: decodeURIComponent(uri.queryKey[val])});
});
uploadParams.push({name: "file", filename: self.filePath, mimeType: contentType}); // If the element is named anything other than 'file', you're likely to receive a MaxPostPreDataLengthExceededError response when upload to S3.
var request = {
url: uploadUrl,
method: "POST"
};
var session = bghttp.session("image-upload");
var task = session.multipartUpload(uploadParams, request);
function onEvent(e) {
console.log("event: " + e.eventName);
if(e.object.description){
console.log(e.object.description);
}
if(e.error){
console.log(e.error);
}
if(e.currentBytes){
console.log(e.currentBytes + " of " + e.totalBytes);
}
if(e.data){
console.log(e.data);
}
}
task.on("progress", onEvent.bind(this));
task.on("error", onEvent.bind(this));
task.on("responded", onEvent.bind(this));
task.on("complete", onEvent.bind(this));
});
关于gist https://gist.github.com/soulfly/b55d6c0dd9448bc1dc1133793a6ac22d的完整代码