您好我想拍张照并将其上传到我的服务器。这是我的nativescript代码如下
运行我的应用程序并拍照后将其发送到服务器。服务器返回错误消息,就像这样
注意:这是我用于nativescript应用程序的标头
var headers = {"Content-Type": "multipart/form-data"}
同样在nativescript中是否有文件系统模块的createReadStream()方法?
答案 0 :(得分:0)
您可以使用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);
});
答案 1 :(得分:0)
以下是文件上传到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
上的完整代码