I want to upload a binary file (images) to an api which accepts application/octet-stream. Unfortunately it seems angular wants to transform my request, which does not work obviously and results in
TypeError: key.charAt is not a function
My request looks like this:
var f = document.getElementById('file_picker').files[0],
r = new FileReader();
r.onloadend = function(e){
var fileData = e.target.result;
$http({
url: '.../upload/' + id,
method: 'PUT',
headers: {'Authorization': 'Bearer asdf',
'Content-Type': 'application/octet-stream'},
data: new Uint8Array(fileData),
transformRequest: []
})
})
r.readAsArrayBuffer(f);
This is my request via curl which works:
curl -i -X PUT -H "Authorization: Bearer asdf" -H "Content-Type: application/octet-stream" --data-binary #jpg.jpg https://.../upload/123
Any ideas? Thanks.
try this:
var fd = new FormData();
fd.append("file", fileObj);
$http({
method: "POST",
params: { 'forcecache': new Date().getTime() },
url: <yoururl>,
headers: {
"Content-Type": undefined
},
transformRequest: angular.identity,
data: fd
});
This is a working example on one of our projects. See http://www.uncorkedstudios.com/blog/multipartformdata-file-upload-with-angularjs/ for more details
Working solution:
var file = document.getElementById('file_picker').files[0],
reader = new FileReader();
reader.onload = function() {
var f = new Uint8Array(reader.result);
$http({
url: '...upload/,
method: 'PUT',
headers: {'Authorization': 'Bearer asdf',
'Content-Type' : undefined},
data: f,
transformRequest: []
});
};
reader.readAsArrayBuffer(file);
The problem is, we have a Data Mapping Interceptor configured, which converts all post and put requests to json. Ouch.
Related
Hello I have tried to use the instagram api to get a connection token. I first tested it on postman and this is what I did:
I used this link to make a request post to the instagram api:
https://api.instagram.com/oauth/access_token?client_id=clientid&client_secret=clientsecret&grant_type=authorization_code&redirect_uri=https://mysite/&code=thecode
The api gives me an error: Missing required field client_id
But when I set the content type to x-www-form-urlencoded everything works fine on postman.
So I tried to do the same thing in javascript with the node module request. I tried to do the same thing as on postman with the module but it does not work... Here is my code:
request(`https://api.instagram.com/oauth/access_token?client_id=clientid&client_secret=clientsecret&grant_type=authorization_code&redirect_uri=https://mysite/&code=` + code, {
method: 'POST',
headers: {"Content-Type": "x-www-form-urlencoded"}
}, (error, response, body) => {
console.log('body:', body)
})
As per MDN, the content type should be application/x-www-form-urlencoded
https://developer.mozilla.org/en-US/docs/Web/HTTP/Methods/POST
Update:
You should read the node doc : https://nodejs.dev/learn/making-http-requests-with-nodejs
Get method:
const https = require('https');
const options = {
hostname: 'api.instagram.com',
path: '/oauth/access_token?client_id=clientid&client_secret=clientsecret&grant_type=authorization_code&redirect_uri=https://mysite/&code=thecode',
method: 'GET',
headers: {
"Content-Type": "application/x-www-form-urlencoded",
"Accept": "Accept-Encoding"
}
};
const req = https.request(options, (res) => {
// ...
});
Post method:
var headers = {
"Content-Type": "application/x-www-form-urlencoded",
"Accept": "Accept-Encoding"
};
var options = {
url: 'https://api.instagram.com/oauth/access_token',
method: 'POST',
headers: headers
};
var form = {
grant_type:'urn:ietf:params:oauth:grant-type:jwt-bearer',
client_id: 'id',
client_secret: 'secret'
redirect_uri : 'https://mysite/&code=thecode'
};
var request = https.request(options, function(response) {
// do stuff
});
request.write(querystring.stringify(form));
request.end();
I am working on React web app with a Flask backend. how can I send a file with JSON data on the body?
I try the code below but is not working
const file = e.target.file[0]
const user = [{name: 'Ma'}]
const formData = new FormData()
dormData.append('file', file)
dormData.append('user', user)
const post = await axios({
method: 'post',
url: 'http://127.0.0.1:5000/route',
data: formData,
headers: { "Content-Type": "multipart/form-data" }
})
You have to set the Content-Type header as application/json and you can set the body as your json
Your code would look something like this
const post = await axios({
method: 'post',
url: 'http://127.0.0.1:5000/route',
headers: { "Content-Type": "application/json" },
body: JSON.stringify(myJson) //insert your stringified json here
})
Since you are creting a react web app, it's easy to structure a JSON from a form.
You are spelling formData wrong. Use this code:
formData.append('file', file)
formData.append('user', user)
I want to to bulk translocation and for that I uploaded the.csv file, its worked for me if I am using curl command but when I used its on node code its showing me error "file not uploaded"
Regarding to curl I am using that code which is working for me :-
curl -F 'data=#/var/www/html/achupload.csv' https://sandbox.usaepay.com/api/v2/bulk_transactions -H "Authorization: Basic X3llMVI3Mk9PdzFHOXBqcW1GaVp2NHJINjRc="
and this is my node code which are showing me error message :-
var request = require('request');
var headers = {
'Authorization': 'Basic X3llMVI3Mk9PdzFHOXBqcW1GaVp2NHJINjRc='
};
var dataString = '#/var/www/html/achupload.csv';
var options = {
url: 'url',
method: 'POST',
headers: headers,
data: dataString
};
console.log("options====",options);
function callback(error, response, body) {
if (!error && response.statusCode == 200) {
console.log(body);
}
else{
console.log("notttttttttttt================",response.body);
}
}
request(options, callback);
How about this modification?
Modification points:
File content is retrieved with fs.createReadStream().
The file is sent as formData.
Modified script:
From:
var request = require('request');
var headers = {
'Authorization': 'Basic ###'
};
var dataString = '#/var/www/html/achupload.csv';
var options = {
url: 'url',
method: 'POST',
headers: headers,
data: dataString
};
To:
var fs = require('fs'); // Added
var request = require('request');
var headers = {
'Authorization': 'Basic ###'
};
var dataString = {data: fs.createReadStream('/var/www/html/achupload.csv')}; // Modified
var options = {
url: 'url',
method: 'POST',
headers: headers,
formData: dataString // Modified
};
Note:
In this modified script, 'Authorization': 'Basic ###' was used. Please be careful this. When you use this, please replace ### to yours.
References:
fs.createReadStream()
multipart/form-data (Multipart Form Uploads)
If this didn't resolve your issue, I apologize.
I'm using fetch to send value to my server. my server is php.
when I send my values with postman my server response as well.
but when I want to send my values with fetch I cannot get them from server side.
postman:
my requestOption:
const requestOptions = {
method: 'POST',
headers: {
'Accept': 'application/json',
'Content-Type': 'application/json',
},
body: JSON.stringify(parms)
};
my values sent to server but I cannot get them like postman form-data.
parms is a object variable. like:
var parms = {};
parms['tok'] = '35345345';
Just use formData as fetch body:
var formData = new FormData()
formData.append("tok", '35345345')
const requestOptions = {
method: 'POST',
headers: {
'Accept': 'application/json'
},
body: formData
};
I want to create a simple AJAX request to my ruby controller, but can not reach current_user.
The JS request:
var myHeaders = new Headers();
myHeaders.append('X-CSRF-Token', "P7qiN53QfDGbHjCXdV8BzL8McxgT1lBkXE3WpjP7taydWrF7d+xkZi+b9fG9TC13IMy61jmGK8pzhmdAoHjlZA==");
var myInit = { method: 'GET',
headers: myHeaders,
};
fetch('/get_user_last_activities.json', myInit).then(function(response) {
if(response.ok) {
console.log(response);
}
throw new Error('Network response was not ok.');
});
I use the 'omniauth-twitter' and 'omniauth-facebook' gems.
The response tells that current_user is nil 🤔
How can I teach my controller to access current_user when rendering .json responses?
It looks like your browser isn't sending the cookie with the fetch request. Try initializing like this:
var myInit = {
method: 'GET',
headers: myHeaders,
credentials: 'same-origin'
};