how to upload file using Angularjs, multipart/form-data - javascript

i want to upload image using Angularjs anyone know how do this..REST API wants
Content-Type:multipart/form-data
www.abc.com/images/id
Request Body
{
// --Boundary_1_1626119499_1392398808202
// Content-Type: image/png
// Content-Disposition: form-data; filename="ducky.png"; modification-date="Wed, 05 Nov 2016 19:53:17 GMT"; size=713915; name="upload_image"
// {binary data truncated for display}
}
my Question is how to upload image file using above rest API, how to assign $scope.tempObject = my Upload image Path
$scope.UploadImage = function () {
var config = {headers: {
'Content-Type': 'multipart/form-data'
}
}
$http.post(properties.customerUploadImage_path + "/"+checkprofile,$scope.tempObject,config).success(function (response) {
Console.log('Uploaded');
});
}

I think you don't use $http the right way.
You can use the headers attribute of the $http service, like this :
$scope.UploadImage = function () {
var config = {
headers: {
'Content-Type': 'multipart/form-data',
}
};
$http({
method: 'POST',
url: properties.customerUploadImage_path + "/" + checkprofile,
data: $scope.tempObject,
config: config,
}).success(function (response) {
console.log('Uploaded');
});
};
I suggest you to take a look at the documentation.

Configure the headers with "Content-Type": undefined and use the FormData API:
var config = { headers: {
"Content-Type": undefined,
}
};
vm.upload = function() {
var formData = new $window.FormData();
formData.append("file-0", vm.files[0]);
$http.post(url, formData, config).
then(function(response) {
vm.result = "SUCCESS";
}).catch(function(response) {
vm.result = "ERROR "+response.status;
});
};
Normally the AngularJS $http service uses Content-Type: application/json. By setting Content-Type: undefined, the framework will omit the Content-Type header and the browser will use its default content type which is multipart/form-data for FormData objects.
Request Header
POST /post HTTP/1.1
Host: httpbin.org
Connection: keep-alive
Content-Length: 388298
Accept: application/json, text/plain, */*
Origin: https://run.plnkr.co
User-Agent: Mozilla/5.0 Chrome/55.0.2883.54 Safari/537.36
Content-Type: multipart/form-data; boundary=----WebKitFormBoundary9lBDT4yoh8lKWtIH
Referer: https://run.plnkr.co/cW228poRVzWs67bT/
Accept-Encoding: gzip, deflate, br
Accept-Language: en-US,en;q=0.8
Request Payload
------WebKitFormBoundary9lBDT4yoh8lKWtIH
Content-Disposition: form-data; name="file-0"; filename="Crop.jpg"
Content-Type: image/jpeg
------WebKitFormBoundary9lBDT4yoh8lKWtIH--
The DEMO on PLNKR.
For more information see,
AngularJS $http Service API Reference -- Setting HTTP Headers
MDN Documents -- FormData API

Related

Random characters in and at the end of a Response body (node.js)

I'm having issues with my node-fetch (specifically, node-fetch-cookies library). I'm supposed to get a string returning from a POST request like:
post_enc=9820CE922B01A166253A29384BA535D7BD08D94FC826A28C67403D19A45AF1CDF5E93DF40C029870DC0D8BD0DFBC9F36C521AF23E7D47CA2156BF917F3CC90B15A848873C3E851170E1C6738C570362E020BCB57FF189044EC611EA6FE2B843A69E248705008E9F2C1CF02030EADA9&post_chk=4A19
BUT I keep getting this instead:
post_enc=9820CE922B01A166253A29384BA535D7BD08D94FC826A28C67403D19A45AF1CDF5E93DF40C029870DC0D8BD0DFBC9F36C521AF23E7D47CA2156BF917F3CC90B15A848873C3E851170E1C6738C570362E020BCB57FF189044EC611EA6FE2B843A69E248705008E9F2C1CF02030EADA9DF4B6694940F35BB80FC9A4E9C6EEA57F08D858648E7979CCF83ADDDA8023E3E2893B6D2A59E86BA9531124251B43042F6F88A924E1B68C876967E2EBA29EEE34C4FD14C70BF0FDBC1A05B70FAC0476916F5C15F9136464D7187045EB>�022343040FB667B00AF2EAA230F90B00FD0E05A70A7102DE856FCB56656CFAB4FEF2C2139048B9CBB5370A500B2893623B61781↑☻¶�♀☻C�
I have tried removing any Accept-Encoding / Content-Encoding headers and I have tried to decode it using zlib but nothing seems to work.
Here's the exact code:
/** #type {any} */
let headers = {
'Content-Type': 'text/plain; charset=UTF-8',
'Content-Encoding': 'gzip, deflate, br', // I've tried removing this...
'Connection': 'keep-alive',
'Accept': '*/*',
'Accept-Language': 'fr-FR,fr;q=0.9,en-US;q=0.8,en;q=0.7',
'Accept-Encoding': 'gzip, deflate, br', // I've tried removing this...
...cfg?.headers,
};
let cookieJar = null;
// Set the session cookie if the last Response had it.
if(this.SessionInfo.SessionCookie != "" && !isLogin) {
cookieJar = new CookieJar();
cookieJar.addCookie(this.SessionInfo.SessionCookie, uri);
headers = { ...headers, "Set-Cookie": this.SessionInfo.SessionCookie };
}
// Make the request.
cfg = { ...cfg, headers, compress: true };
const res = await fetch(cookieJar, uri, cfg);

No file was submitted when try to send generated PDF file from React Js to Django-Rest Post request

Trying to generate pdf file in react js and then sending it to the django rest backend.
I have successfully created the pdf file using jsPDF and html2canvas, but now unable to send to the rest api, whenever I submit it gives me response "No file was submitted".I have checked django-rest api's and its working fine, the pdf is not going to the rest api's.Here's my below code:
genPDF=(evt)=>{
evt.preventDefault();
html2canvas(document.getElementById("pdfid")).then(canvas=>{
let img=canvas.toDataURL('img/png');
let doc=new JsPDF();
doc.addImage(img,'JPEG',30,30);
//doc.save('test.pdf');
let file=doc;
const formdata=new FormData();
formdata.append("file",file);
this.postpdf(formdata)
});
};
postpdf=(payload)=>{
fetch(`http://127.0.0.1:8000/chauffeur/pdf_upload/`,
{
method: 'POST',
body: JSON.stringify(payload),
headers: {
'Content-Type': 'application/json'
}
}
).then(response => response.json()).catch(error => console.error('Error:', error));
};
Request Headers
Content-Type: multipart/form-data; boundary=----
WebKitFormBoundaryEueEwtpzbquHU6Tb
Origin: http://localhost:3000
Referer: http://localhost:3000/contractinvoice
User-Agent: Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko)
Chrome/73.0.3683.86 Safari/537.36
Response Headers
Access-Control-Allow-Credentials: true
Access-Control-Allow-Origin: http://localhost:3000
Allow: GET, POST, HEAD, OPTIONS
Content-Length: 76
Content-Type: application/json
Date: Wed, 10 Apr 2019 05:44:49 GMT
Server: WSGIServer/0.2 CPython/3.5.2
Vary: Accept, Cookie, Origin
X-Frame-Options: SAMEORIGIN
I think I am sending the file in a wrong but can't sort it what's the problem,need for suggestions.Thanks
You have error here:
'Content-Type': 'application/json'
If you want to send file, you should use multipart/form-data
why do you want to convert payload to JSON.stringify()... payload is not json...
try this...
postpdf=(payload)=>{
fetch(`http://127.0.0.1:8000/chauffeur/pdf_upload/`,
{
method: 'POST',
body: payload,
headers: {
'Content-Type': 'multipart/form-data'
}
}
).then(response => response.json()).catch(error => console.error('Error:', error));
};

Unable to Post in Angular / Express

I am trying to post using angular but keep getting a 404 error. It looks like the request is not being made. Any ideas why? Thanks for all the help.
var param = $scope.tag;
// client
$http({method: 'Post', url: '/api', headers: {
"Content-Type": "application/json", "Access-Control-Allow-Origin": "*" }, data: {tag: param}})
.then(function(response) {
console.log(response);
});
// server
app.post('/api', function (req, res) {
var tag = req.body.tag;
request("http://food2fork.com/api/search?key=KEY&q=" + tag, function (req, res) {
res.json(response);
});
});
// request headers
Accept:application/json, text/plain, */*
Accept-Encoding:gzip, deflate
Accept-Language:en-US,en;q=0.8
Access-Control-Allow-Origin:*
Cache-Control:no-cache
Connection:keep-alive
Content-Length:17
Content-Type:application/json
Host:localhost:3000
// response headers
Connection:keep-alive
Content-Length:22
Content-Type:text/html; charset=utf-8
Date:Sat, 19 Sep 2015 23:22:15 GMT
X-Content-Type-Options:nosniff
X-Powered-By:Express
You should not have to use all that code. Try:
// Client:
var tag = $scope.tag;
$http.post('/api', {tag: tag})
.then(function(response) {
console.log(response);
});
//Server:
var bodyParser = require('body-parser');
app.use(bodyParser.json());
app.post('/api', function(req, res) {
var tag = req.body.tag;
res.send(tag);
});
Use method: 'POST' instead of method:'Post'.
The latter is not recognized and a default GET is emitted instead that the POST you expect.
edit: checked the code and what I wrote above is not true
In addition to that...shouldn't be some URL like
/api/tags
???

Making a PUT request results in an OPTIONS request being sent first before the PUT, why does the browser behave this way?

When i send a POST request, it's ok. But when i send a PUT request (replace $http.post() to $http.put()) Angular send an OPTIONS request without datas, wait the response and send a PUT request with datas.
It's not a CORPS problem because it's the client which send 2 requests.
For the OPTIONS request, the JSON response isn't parsed because Angular doesn't go to the success function.
I want to Angular not send the OPTIONS request.
Do you know this problem ? Do you know a fix ?
The code :
var app = angular.module('myApp', []);
app.config(function($httpProvider) {
delete $httpProvider.defaults.headers.common['X-Requested-With'];
$httpProvider.defaults.headers.post['Content-Type'] = 'application/x-www-form-urlencoded; charset=UTF-8';
$httpProvider.defaults.headers.put['Content-Type'] = 'application/x-www-form-urlencoded; charset=UTF-8';
$httpProvider.defaults.useXDomain = true;
//
var param = function(obj) {
var query = '', name, value, fullSubName, subName, subValue, innerObj, i;
for(name in obj) {
value = obj[name];
if(value instanceof Array) {
for(i=0; i<value.length; ++i) {
subValue = value[i];
fullSubName = name + '[' + i + ']';
innerObj = {};
innerObj[fullSubName] = subValue;
query += param(innerObj) + '&';
}
}
else if(value instanceof Object) {
for(subName in value) {
subValue = value[subName];
fullSubName = name + '[' + subName + ']';
innerObj = {};
innerObj[fullSubName] = subValue;
query += param(innerObj) + '&';
}
}
else if(value !== undefined && value !== null) {
query += encodeURIComponent(name) + '=' + encodeURIComponent(value) + '&';
}
}
return query.length ? query.substr(0, query.length - 1) : query;
};
// Override $http service's default transformRequest (json to application/x-www-form-urlencoded)
$httpProvider.defaults.transformRequest = [function(data) {
return angular.isObject(data) && String(data) !== '[object File]' ? param(data) : data;
}];
});
app.controller('login', function ($scope, $http) {
$scope.run = function() {
var file_data = $("#file").prop("files")[0];
var datas = {email:"email#domain.com", pass:sha1("xxxxxx")};
$http.put("http://myapi.com/user/connect", datas
).success(function(data, status, headers, config) {
console.log(data);
}).error(function(data, status, headers, config) {
});
return;
}
});
The first request :
General
Remote Address:127.0.0.1:80
Request URL:http://api.wezit.local/user/connect
Request Method:OPTIONS
Status Code:200 OK
Response Headers
Access-Control-Allow-Methods:POST, GET, PUT, DELETE
Access-Control-Allow-Origin:*
Cache-Control:no-cache, must-revalidate
Connection:Keep-Alive
Content-Length:170
Content-Type:application/json;
Date:Fri, 17 Jul 2015 16:31:15 GMT
Expires:Mon, 26 Jul 1997 05:00:00 GMT
Keep-Alive:timeout=5, max=100
Pragma:no-cache
Server:Apache/2.4.10 (Fedora) PHP/5.5.25
Set-Cookie:PHPSESSID=2dj440b2vr2emi5ht9ojcl8gk6; path=/
Set-Cookie:PHPSESSID=q3pg80qb43ps6tpkljlvelo0k7; path=/
X-Powered-By:PHP/5.5.25
Request Headers
Accept:*/*
Accept-Encoding:gzip, deflate, sdch
Accept-Language:fr-FR,fr;q=0.8,en-US;q=0.6,en;q=0.4
Access-Control-Request-Headers:accept, content-type
Access-Control-Request-Method:PUT
Connection:keep-alive
Host:api.wezit.local
Origin:http://test.local
Referer:http://test.local/api.php
User-Agent:Mozilla/5.0 (X11; Linux i686 (x86_64)) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/43.0.2357.125 Safari/537.36
The second request :
General
Remote Address:127.0.0.1:80
Request URL:http://api.wezit.local/user/connect
Request Method:PUT
Status Code:200 OK
Response Headers
Access-Control-Allow-Methods:POST, GET, PUT, DELETE
Access-Control-Allow-Origin:*
Cache-Control:no-cache, must-revalidate
Connection:Keep-Alive
Content-Length:327
Content-Type:application/json;
Date:Fri, 17 Jul 2015 16:31:15 GMT
Expires:Mon, 26 Jul 1997 05:00:00 GMT
Keep-Alive:timeout=5, max=99
Pragma:no-cache
Server:Apache/2.4.10 (Fedora) PHP/5.5.25
Set-Cookie:PHPSESSID=18jfhgq2fs1p1f1nu7ua1ap8c3; path=/
Set-Cookie:PHPSESSID=14aifglpntf8amavkipclvom67; path=/
X-Powered-By:PHP/5.5.25
Request Headers
Accept:application/json, text/plain, */*
Accept-Encoding:gzip, deflate, sdch
Accept-Language:fr-FR,fr;q=0.8,en-US;q=0.6,en;q=0.4
Connection:keep-alive
Content-Length:142
Content-Type:application/x-www-form-urlencoded; charset=UTF-8
Host:api.wezit.local
Origin:http://test.local
Referer:http://test.local/api.php
User-Agent:Mozilla/5.0 (X11; Linux i686 (x86_64)) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/43.0.2357.125 Safari/537.36
Form Data
email:email#domain.com
pass:ce35927f4dcb044bceda5f385823419cb0156507
Browsers always make a pre-flight request with the OPTION method, when you initiate a cross-origin request. That means the API you are trying to access is on a different origin from your application. There's nothing you can do about this.
Do you know this problem?
There is no problem in what you observed, it is the expected behaviour.
When i send a POST request, it's OK.
Here's the reason why it's OK:
In particular, a request is preflighted if:
It uses methods other than GET, HEAD or POST. Also, if POST is used to send request data with a Content-Type other than
application/x-www-form-urlencoded, multipart/form-data, or text/plain,
e.g. if the POST request sends an XML payload to the server using
application/xml or text/xml, then the request is preflighted.
It sets custom headers in the request (e.g. the request uses a header such as X-PINGOTHER)

AngularJS can't use Basic Authentication

I've problem with settings header. My js script
var invocation = new XMLHttpRequest();
var url = 'http://example.com/api/auth';
var handler = [];
if(invocation) {
invocation.open('GET', url, true);
invocation.setRequestHeader('X-PINGOTHER', "DDD");
invocation.setRequestHeader('Access-Control-Allow-Origin', "http://localhost");
invocation.setRequestHeader('Access-Control-Request-Headers', true);
invocation.onreadystatechange = handler;
invocation.send();
}
Header from firebug:
OPTIONS /api/auth HTTP/1.1
Host: example.com
User-Agent: Mozilla/5.0 (Windows NT 6.2; WOW64; rv:18.0) Gecko/20100101 Firefox/18.0 FirePHP/0.7.4
Accept: text/html,application/xhtml+xml,application/xml;q=0.9,*/*;q=0.8
Accept-Language: en-US,en;q=0.5
Accept-Encoding: gzip, deflate
Origin: http://localhost
Access-Control-Request-Method: GET
Access-Control-Request-Headers: access-control-allow-origin,x-pingother
x-insight: activate
Connection: keep-alive
As you can see it always adds to the Access-Control-Request-Headers as value, and sets OPTIONS no GET. Any idea?
You should use the $http that comes with AngularJS, much better:
$http.defaults.useXDomain = true; //enable cors
$http({
method: 'GET',
url: 'http://example.com/api/auth',
headers: {'X-PINGOTHER': 'DDD'}
});
All right, it's working, but not with GET.
How it's should be:
$http({
method: "GET",
url: "http://example.com/api/auth"
}).success(function(data) {
$scope.user = data;
}).error(function(data) {
console.log("error");
});
Working example :
$http.jsonp('http://example.com/api/auth?&callback=JSON_CALLBACK')
.success(function(data){
console.log(data);
}).error (function(data){
alert("eerrror");
});
It works only with JSONP.

Categories

Resources