Getting Bad method 405 response while trying to upload a file to Google Cloud Storage using SAP ui5 - file-upload

I am trying to upload a file to Google Cloud Storage using a basic uploader in UI5.
When I am uploading the file, I am getting a 405 error in my response.
My controller code goes like this.
Please let me know if I am making any mistake anywhere.
sap.ui.define(['sap/m/MessageToast','sap/ui/core/mvc/Controller'],
function(MessageToast, Controller) {
"use strict";
return Controller.extend("sap.ui.unified.sample.FileUploaderBasic.Controller", {
handleUploadComplete: function(oEvent) {
var sResponse = oEvent.getParameter("response");
if (sResponse) {
var sMsg = "";
var m = /^\[(\d\d\d)\]:(.*)$/.exec(sResponse);
if (m[1] == "200") {
sMsg = "Return Code: " + m[1] + "\n" + m[2] + "(Upload Success)";
oEvent.getSource().setValue("");
} else {
sMsg = "Return Code: " + m[1] + "\n" + m[2] + "(Upload Error)";
}
MessageToast.show(sMsg);
}
},
handleUploadPress: function() {
var oFileUploader = this.byId("fileUploader");
var prop = oFileUploader.getValue();
var path = oFileUploader.getUploadUrl();
MessageToast.show(prop);
MessageToast.show(path);
// var form = new FormData();
//form.append("files", fileInput.files[0],"C:\Users\i347520\Desktop\pan.jpg");
/*eslint-disable*/
var settings = {
"url": "https://storage.googleapis.com/upload/storage/v1/b/testocr-1234/o?uploadType=media&name=prop"
/*eslint-enable*/
};
oFileUploader.upload(settings);
}
});
});
View:
<mvc:View
controllerName="sap.ui.unified.sample.FileUploaderBasic.Controller"
xmlns:l="sap.ui.layout"
xmlns:u="sap.ui.unified"
xmlns:mvc="sap.ui.core.mvc"
xmlns="sap.m"
class="viewPadding">
<l:VerticalLayout>
<u:FileUploader
id="fileUploader"
name="myFileUpload"
uploadUrl="upload/"
tooltip="Upload your file to the local server"
uploadComplete="handleUploadComplete"/>
<Button
text="Upload File"
press="handleUploadPress"/>
</l:VerticalLayout>
</mvc:View>

Related

openui5 FileUploader not working

I am trying to upload a file with a simple form. I can choose a file but when I click on "upload" nothing happens.
My FileUploader.view.xml is like:
<mvc:View
controllerName="sap.ui.unified.sample.FileUploaderBasic.Controller"
xmlns:l="sap.ui.layout"
xmlns:u="sap.ui.unified"
xmlns:mvc="sap.ui.core.mvc"
xmlns="sap.m"
class="viewPadding">
<l:VerticalLayout>
<u:FileUploader
id="fileUploader"
name="myFileUpload"
uploadUrl="upload/"
width="400px"
tooltip="Upload your file to the local server"
uploadComplete="handleUploadComplete"/>
<Button
text="Upload File"
press="handleUploadPress"/>
</l:VerticalLayout>
My Contoller.controller.js
sap.ui.define(['sap/m/MessageToast','sap/ui/core/mvc/Controller'],
function(MessageToast, Controller) {
"use strict";
var ControllerController = Controller.extend("sap.ui.unified.sample.FileUploaderBasic.Controller", {
handleUploadComplete: function(oEvent) {
var sResponse = oEvent.getParameter("response");
if (sResponse) {
var sMsg = "";
var m = /^\[(\d\d\d)\]:(.*)$/.exec(sResponse);
if (m[1] == "200") {
sMsg = "Return Code: " + m[1] + "\n" + m[2] + "(Upload Success)";
oEvent.getSource().setValue("");
} else {
sMsg = "Return Code: " + m[1] + "\n" + m[2] + "(Upload Error)";
}
MessageToast.show(sMsg);
}
},
handleUploadPress: function(oEvent) {
var oFileUploader = this.getView().byId("fileUploader");
oFileUploader.upload();
}
});
return ControllerController;
});
When I run this in the debugger I get an Uncaught TypeError:
Uncaught TypeError: Cannot read property '1' of null
at f.handleUploadComplete (FileUploader.controller.js?eval:11)
at f.a.fireEvent (EventProvider-dbg.js:229)
at f.a.fireEvent (Element-dbg.js:427)
at f.fireUploadComplete (ManagedObjectMetadata-dbg.js:426)
at HTMLIFrameElement.eval (FileUploader.js?eval:6)
at HTMLIFrameElement.dispatch (jquery-dbg.js:4737)
at HTMLIFrameElement.c3.handle (jquery-dbg.js:4549)
if (m[1] == "200") {
sMsg = "Return Code: " + m[1] + "\n" + m[2] + "(Upload Success)";
oEvent.getSource().setValue("");
I searched for sample code and it seems my code is ok, but I don't know why I can't upload a file by click on the button.
I solved this problem ! :)
So, instead of using this
var m = /^[(\d\d\d)]:(.)$/.exec(sResponse);
use this in view FileUploader :
sendXHR="true"
After, on controller js you can use for status :
oEvent.getParameter("status")
and for getting answer as a json file :
var jsonfile = JSON.parse(oEvent.getParameter("responseRaw"));
Then access your sent object attributes from server (only when use dataType: 'json')
jsonfile.attribute
I hope this helps a lot!

How to save or open a pdf file in pdf Viewer from response titanium

I want to open pdf file on click.
I tried below code but it didn't help me. It is giving error could not read file
var xhr = Ti.Network.createHTTPClient({
onload : function(e) {
var f = Ti.Filesystem.getFile(Ti.Filesystem.applicationDataDirectory, 'file.pdf');
Ti.API.info('file == ' + f);
Ti.API.info('response = ' + this.responseData);
Ti.API.info('response = ' + JSON.stringify(this.responseData));
f.write(this.responseData);
Ti.API.info('write file == ' + f.write(this.responseData));
Ti.API.info('filepath == ' + f.nativePath);
Ti.API.info('get filepath == ' + f.getNativePath());
Ti.Android.currentActivity.startActivity(Ti.Android.createIntent({
action : Ti.Android.ACTION_VIEW,
type : 'application/pdf',
data : f.nativePath
}));
},
onerror : function(e) {
Alloy.Globals.loading.hide();
alert("Cannot retrieve PDF form web site");
},
timeout : 5000
});
xhr.open('GET', "https://www.mbta.com/uploadedfiles/Documents/Schedules_and_Maps/Rapid%20Transit%20w%20Key%20Bus.pdf");
xhr.send();
But I am getting Error as The document path is not valid.
I tried different way also using webview still not getting pdf on my app.
var win = Ti.UI.createWindow({
backgroundColor : '#fff'
});
var pdfViewer = Ti.UI.createWebView({
url : "http://lkn.ccomsys.com/assets/media/datafiles/gov/vvvv_Shehnai_Order1.pdf",
width : Titanium.UI.SIZE,
height : Titanium.UI.SIZE
});
Ti.API.info('pdfviewer == ' + JSON.stringify(pdfViewer));
win.add(pdfViewer);
win.open();
Thanks in advance.
I sorted this out
Step 1 : Created directory and file.
Step 2 : Write response to created file.
Step 3 : Open pdf with android intent.
Below is the complete code
var xhr = Ti.Network.createHTTPClient({
onload : function(e) {
Alloy.Globals.loading.hide();
var Settings = Titanium.Filesystem.getFile(Titanium.Filesystem.tempDirectory, 'Settings');
Ti.API.info("Created Settings: " + Settings.createDirectory());
Ti.API.info('Settings ' + Settings);
var newFile = Titanium.Filesystem.getFile(Settings.nativePath, 'Setting.pdf');
Ti.API.info('new file == ' + newFile);
if (newFile.exists() === false) {
// you don't need to do this, but you could...
newFile.write(this.responseData);
}
Ti.API.info('response = ' + this.responseData);
Ti.API.info('response = ' + JSON.stringify(this.responseData));
if (newFile.exists()) {
newFile.write(this.responseData);
Ti.API.info('newfile: ' + newFile.read());
}
Ti.Android.currentActivity.startActivity(Ti.Android.createIntent({
action : Ti.Android.ACTION_VIEW,
type : 'application/pdf',
data : newFile.nativePath
}));
},
onerror : function(e) {
Alloy.Globals.loading.hide();
alert("Cannot retrieve PDF form web site");
},
timeout : 5000
});
xhr.open('GET', "https://www.mbta.com/uploadedfiles/Documents/Schedules_and_Maps/Rapid%20Transit%20w%20Key%20Bus.pdf");
xhr.send();

How do I retrieve the URL of a file hosted on Parse-Server through Javascript?

My code so far:
<script type="text/javascript">
var username = sessionStorage.getItem('username', username);
var password = sessionStorage.getItem('password', password);
var Image = Parse.Object.extend("Image");
var query = new Parse.Query(Image);
query.equalTo("username", username);
query.descending("createdAt");
query.find({
success: function(results) {
alert("Successfully retrieved " + results.length + " images.");
// Do something with the returned Parse.Object values
for (var i = 0; i < results.length; i++) {
var object = results[i];
var url = (object.get("image").url);
var createdAt = (object.get("createdAt"));
var image = object.get("image");
alert(url + object.id + createdAt + username + image);
}
},
error: function(error) {
alert("Error: " + error.code + " " + error.message);
}
});
</script>
All variables return the expected values except "image" which returns [Object object] and url which returns function url(){ return this._url;}
in order to get the file URL you need to do the following :
var image = object.get("image"); // here you have ParseFile
var imageUrl = image.url(); // now you have the file URL

Mailgun - Attach a file in phantomjs

I am trying to make a application using phantomjs which requires mailgun service to send email. Since there is no official mailgun phantomjs library, I am facing some troubles with attaching files in the emails. The email is dispatched successfully but I dont see any attachment to it.
Here is the code:
function ObjToQs(obj) {
var str = "";
for (key in obj) {
str += key + '=' + obj[key] + '&';
}
str = str.slice(0, str.length - 1);
return str;
}=
var page = require('webpage').create(),
url = 'https://api.mailgun.net/v3/sandboxbxxxxxxxxxxxxxxxxxxxxxxxx.mailgun.org/messages',
data = {
from: "Ganesh <mail#gmail.com>",
to: "email#gmail.com",
subject: "subject!",
text: "Body",
attachment: '/path/test.txt'
};
console.log(ObjToQs(data));
page.customHeaders = {'Authorization': 'Basic ' + btoa('api:key-xxxxxxxx')};
page.open(url, 'post', ObjToQs(data), function (status) {
if (status !== 'success') {
console.log('FAIL to load the log');
console.log(status);
} else {
console.log('Log success');
var result = page.evaluate(function () {
return document.body.innerText;
});
console.log("log Result: " + result);
phantom.exit();
}
});
What should I do?
Thanks!
This will work for you -- it's a NodeJS lib for mailgun: https://www.npmjs.com/package/mailgun-js

Uploaded image on parse.com gives 403 error

I am trying to upload image to parse.com using REST API, and associating to an object as shown in docs
I am getting the fileUrl from phonegap / appgyver-supersonic camera api.
The Image is uploaded successfully and also associated successfully to the "receipt" object but accessing the url gives 403 error.
How do I access the URL and view the uploaded image, I get a white page (with broken image icon) and 403 error.
File :
http://files.parsetfss.com/68087456-8a5a-403a-820f-13912d2c0911/tfss-5d0edbdb-730b-4cd6-a44f-f0ce1e2ab120-pic.jpg
My receipt class has public write/read access.
Here is my code :
$scope.send = function(fileURL, mimeType){
function win(r) {
$scope.textvar = r;
var response = JSON.parse(r.response);
console.log("Code = " + r.responseCode);
console.log("Response = " + r.response);
console.log("Sent = " + r.bytesSent);
var req = {
method: 'POST',
url: 'https://api.parse.com/1/classes/receipt',
headers: {
'X-Parse-Application-Id':'XXXXXXXXXXXXX',
'X-Parse-REST-API-Key':'XXXXXXXXXXXXXXXX',
"Content-Type": "application/json"
},
data: {"name": "user_receipts",
"images": {
"name": response.name,
"__type" : "File"
}
}
}
$http(req).success(function(data, status, headers, config) {
// this callback will be called asynchronously
// when the response is available
console.log("image association success ");
console.log(data);
console.log(headers);
console.log(status);
console.log(config);
}).
error(function(data, status, headers, config) {
// called asynchronously if an error occurs
// or server returns response with an error status.
});
}
function fail(error) {
console.log("An error has occurred: Code = " + error.code);
console.log("upload error source " + error.source);
console.log("upload error target " + error.target);
console.log("upload error http-code " + error.http_status);
}
var uri = encodeURI("https://api.parse.com/1/files/pic.jpg");
var options = new FileUploadOptions();
options.fileKey="data-binary";
options.fileName=fileURL.substr(fileURL.lastIndexOf('/')+1);
options.mimeType=mimeType;
var headers = {"X-Parse-Application-Id": "XXXXXXXXXXXXXXXXX",
"X-Parse-REST-API-Key":"XXXXXXXXXXXXXXXX",
"Content-Type":"image/jpeg"};
options.headers = headers;
var ft = new FileTransfer();
ft.onprogress = function(progressEvent) {
if (progressEvent.lengthComputable) {
console.log("length : "+progressEvent.loaded/progressEvent.total);
} else {
console.log("loaded : "+progressEvent.loaded);
}
};
ft.upload(fileURL, uri, win, fail, options);
};
I have wasted 5 days on this already, Please Help.
I am no expert in either appgyver / phonegap or parse.com