how to submit json file in sencha touch in http post multipart? - sencha-touch

I want to submit json file form sencha touch to my tomcat server using http post multipart but i don't know how to do ?
can any one give me some idea or example.
Thanks

you can do this using jQuery.
var request = new FormData();
$.each(context.prototype.fileData, function(i, obj) { request.append(i, obj.value.files[0]); });
request.append('action', 'upload');
request.append('id', response.obj.id);
$.ajax({
type : 'POST',
url : context.controller,
data : request,
processData : false,
contentType : false,
success : function(r) {
console.log(r);
//if (errors != null) { } else context.close();
},
error : function(r) { alert('jQuery Error'); }
});

Related

ReactNative: uploading image file to server using Axios is not working

I am building a mobile application using ReactNative. My app needs to upload image file to the server. I am using Axios for that. But the file is always empty on the server-side.
This is my code.
const makeMultipartFormDataRequest = async ({
path,
data = null,
headers = null
}) => {
let accessToken = await getAccessToken();
if (accessToken) {
if (headers == null) {
headers = {
'Authorization': `Bearer ${accessToken}`
}
} else {
headers.Authorization = `Bearer ${accessToken}`;
}
}
let formData = new FormData();
if (data) {
for (let prop in data) {
let field = null;
if (typeof data[prop] == "object" && data[prop]?.mime) {
field = {
uri: data[prop].uri,
name: data[prop].name,
type: data[prop].mime
}
} else {
field = data[prop];
}
// here image file is added proof_file field
formData.append(prop, field);
}
}
let url = config.apiEndpoint + path;
return axios.post(url, formData, {
headers: headers
});
}
As you see in the code, I put a comment where I put the file into the request. When I log the value in the console, I got this.
{"name": "IMG_0003.JPG", "type": "image/jpeg", "uri": "/Users/waihein/Library/Developer/CoreSimulator/Devices/ED2E89F7-F8C9-498E-9B80-41E13814A480/data/Containers/Data/Application/6AEBDAD9-A84C-4B33-95E5-0180F09B1AD5/tmp/react-native-image-crop-picker/E3B07A1B-B79D-43A0-A649-E05F8500783B.jpg"}
But the file is never sent in the request. What is wrong with my code and how can I fix it?
As you are sending form data you should specify that in the content type. Something like this,
headers: { "Content-Type": "multipart/form-data" }

how to download a pdf file from an url in angular 5

I currently spend one day in this issue,still failed to download a file from an url in angular 5
leadGenSubmit() {
return this.http.get('http://kmmc.in/wp-content/uploads/2014/01/lesson2.pdf',
{responseType:ResponseContentType.Blob}).subscribe((data)=>{
console.log(data);
var blob = new Blob([data], {type: 'application/pdf'});
console.log(blob);
saveAs(blob, "testData.pdf");
},
err=>{
console.log(err);
}
)
}
when I run above code it shows following error
ERROR TypeError: req.responseType.toLowerCase is not a function
at Observable.eval [as _subscribe] (http.js:2187)
at Observable._trySubscribe (Observable.js:172)
how can I solve this issue.Can any one post the correct code to download a pdf file from an url in angular 5?
I think you should define header and responseType like this:
let headers = new HttpHeaders();
headers = headers.set('Accept', 'application/pdf');
return this.http.get(url, { headers: headers, responseType: 'blob' });
Here is my simple solution to open a PDF based on an ID in Angular :
In my service, I created this method :
public findById(id?: string): Observable<Blob> {
return this.httpClient.get(`${this.basePath}/document/${id}`, {responseType: 'blob'});
}
Then in my component, I can do use this method (behind a button or whatever):
showDocument(documentId: string): void {
this.yourSuperService.findById(documentId)
.subscribe((blob: Blob): void => {
const file = new Blob([blob], {type: 'application/pdf'});
const fileURL = URL.createObjectURL(file);
window.open(fileURL, '_blank', 'width=1000, height=800');
});
}
Try this
let headers = new HttpHeaders();
headers = headers.set('Accept', 'application/pdf');
return this.http.get(url, { headers: headers, responseType: 'blob' as 'json' });
References:
Discussion on Angular Github
Stackoverflow

Angular 2 RC 5 Attempting to Get and Display a PDF from a Server

I am trying to display a PDF that is generated from a server onto a view in my Angular 2 RC 5 project. Right now, the ASPNETCORE server is returning the object as an 'application/pdf' and the Angular client is trying to parse the response as a blob. However, I get the following error on the client side:
Error: The request body isn't either a blob or an array buffer
The code that I'm using to call the PDF server is essentially:
getHeaders() : Headers {
var headers = new Headers({
'responseType': 'application/blob'
});
return headers;
}
getBlob() {
return this.http.get(uri, new RequestOptions({headers: this.getHeaders()}, body: "" }))
.map(response => (<Response>response).blob());
}
Try to set the responseType to Blob, it should work:
getBlob() {
return this.http.get(uri, {responseType: ResponseContentType.Blob})
.map(response => (<Response>response).blob());
}
Work's for me :
Component :
downloadInvoice(invoice) {
this.loading = true;
this.invoiceDataService
.downloadInvoice(invoice)
.subscribe(
(blob) => {
FileSaver.saveAs(blob, 'test.pdf');
},
error => this.error = error,
() => {
this.loading = false;
console.log('downloadInvoices : Request Complete')
}
)
}
Data service :
downloadInvoice(invoice): Observable<Blob> {
return this.api.downloadInvoice(invoice);
}
Api service :
downloadInvoice(invoice: Invoice): Observable<Blob> {
return this.authHttp
.get(this.apiBase + '/invoices/' + invoice.hashid + '/download', {responseType: ResponseContentType.Blob})
.map(response => {
return new Blob([response.blob()], {type: 'application/pdf'});
})
.catch(this.handleError.bind(this));
}
Enjoy :)
For Angular 5, ResponseContentType has been deprecated, so a current solution I found was to use:
getFile(): Observable<File> {
let options = {
headers: new HttpHeaders({ 'Content-Type': 'application/json' }),
responseType: 'blob' as 'json'
};
return this.http.get<File>(uri, options);
}

Adapter request does not return expected data

My worklight app has a page to post some values to a remote server. This is done using an adapter which calls the url to post. The client javascript is:
var invocationData = {
adapter : 'StoryAdaptor',
procedure : 'postStoryDetails',
parameters : [ storyParameters ]
};
WL.Client.invokeProcedure(invocationData, {
onSuccess : function(data) {
alert("return message: "+JSON.stringify(data))
},
onFailure : function(data) {
alert("Couldn't save Story");
}
});
The adapter method is
function postStoryDetails(storyParameters){
var input = {
method : 'post',
returnedContentType : 'json',
path : "/postStory.json",
parameters : storyParameters
};
var authResult = WL.Server.invokeHttp(input);
}
The remote application is a java Spring application which takes the parameters and on successful save, returns just a string "success".
#RequestMapping(value = { "/postStory" }, method = RequestMethod.POST)
public String postStory(HttpServletRequest request,HttpServletResponse response){
Story story = new Story();
story.setTitle(request.getParameter("title"));
.
.
.
boolean status = storyService.saveStory(story);
if(status ){
return "success";
}
return "failed";
}
I am not getting the "success" message in worklght. Instead, each time, the alert is printing
return message: {"status":200,"invocationContext":null,"invocationResult":{"isSuccessful":true}}
Why I am not getting my returned message?
Try returning like the following:
return {
result: "success";
}
For Worklight 6.2, see Using Java in Adapters, slide #11
For MobileFirst Platform 3.2, see Using Java in Adapters, section "Invoking custom Java classes from the adapter"

How to get the response after a POST request in CasperJS

I have this very simple code to read the response from a server endpoint after a post request. Actually I'm saving a data to a database and wait for a response before going to next step
casper.open('http://example.com/ajax.php, {
method: 'POST',
data: {
'title': '<title>',
'unique_id': '<unique_id>'
}
});
on ajax.php file I'm trying to echo the POST request in a simple way.
this will let me know easily if I'm getting the right response from the server.
echo json_encode($_POST);
I tried these snippets but I'm unable to get the response.
casper.on('page.resource.received', function(resp){
this.echo(JSON.stringify(resp, null, 4));
});
casper.on('http.status.200', function(resp){
this.echo(JSON.stringify(resp, null, 4));
});
casper.on('resource.received', function(resp) {
this.echo(JSON.stringify(resp, null, 4));
});
I've been facing the same problem POSTing a query to ElasticSearch and I could not retrieve the results.
As far as I can understand if you want to retrieve the data echoed by your script the solution could be this:
this.echo(this.page.content);
or
this.echo(this.page.plainText);
in your function.
For example (my case with ElasticSearch):
/*
* SOME VAR DEFINITIONS HERE
*/
casper.start();
casper.then( function() {
// the next var is very specific to ElasticSearch
var elasticQuery = JSON.stringify (
{
'size' : 20,
'query' : {
'filtered' : {
'filter' : { 'term' : { 'locked' : false } }
}
},
'sort': { 'lastScrapeTime': { 'order': 'asc' } }
}
);
var elasticRequest = {
method: 'POST',
data: elasticQuery
}
this.thenOpen( <<YOUR URL>>, elasticRequest, function (response) {
// dump response header
require('utils').dump(response);
// echo response body
this.echo(this.page.content);
// echo response body with no tags added (useful for JSON)
this.echo(this.page.plainText);
});
}
);
casper.run();
As Roberto points out. You can use this.page.content to show the response. But you need to add the function(response) in your script. For example:
casper.open('http://example.com/ajax.php', {
method: 'POST',
data: {
'title': '<title>',
'unique_id': '<unique_id>'
}
}, function(response){
if(response.status == 200){
require('utils').dump(this.page.content);
}
});
If you want to unit test a REST API, CasperJS is not necessarily the right tool.
CasperJS allows to observe a web browser which is running a web page.
So a more typical approach would be to use CasperJS to load a page that would call your REST API and you would assert the page behavior is correct (assuming the page would make something observable according the AJAX call response).