Image or file corrupted when success upload - javascript

Hi im trying to upload file or image in my dropbox using dropzone. and when it successfully upload in my dropbox it just corrupted it cant be preview.. I was wondering if there's a problem with my codes in getting a file
This is my processing method inside of my init: function()
this.on("processing", function(file) {
var url = 'https://content.dropboxapi.com/2/files/upload';
var file = dropzone.files[0];
var filename = file.name;
$.ajax({
url: url,
type: 'post',
processData: false,
contentType: 'application/octet-stream',
headers: {
"Authorization": "ACCESS TOKEN",
"Dropbox-API-Arg": '{"path": "/'+filename+'","mode": "add"}'
},
success: function (data){
alert('Success Upload');
/*this.options.url = url;*/
console.log(data);
}
})
});

Mmm may be you are not uploading the file with the proper headers. If you can please use curl first instead of using javascript so you can check faster if your file is being uploaded or not.
https://www.dropbox.com/developers/documentation/http/documentation#files-upload
I don't know if you have already checked the API documentation, first test it using curl and then form the packet using javascript.
curl -X POST https://content.dropboxapi.com/2/files/upload \
--header "Authorization: Bearer TOKEN
" \
--header "Dropbox-API-Arg: {\"path\": \"/Homework/math/Matrices.txt\",\"mode\": \"add\",\"autorename\":
true,\"mute\": false}" \
--header "Content-Type: application/octet-stream" \
--data-binary #local_file.txt
I hope this can help you...

Have you checked your internet connection? I ask because I had a similar problem, and even though my network was "fast", turns out my network is a burst type of network and the image was only uploading 2 of the 5 mb file size before the burst traffic timed out.
Crazy I know, but if you think that not might be the issue. Have you debugged this script yet? Are you getting your alert on screen and in your console debugger?

Related

YouTubeAPI: How to upload thumbnail (JS)

I tried uploading thumbnail on youtube using this guide: https://developers.google.com/youtube/v3/docs/thumbnails/set
I was able to successfully run it on postman using this curl:
curl --location --request POST 'https://www.googleapis.com/upload/youtube/v3/thumbnails/set?videoId=<video id>' \
--header 'Authorization: OAuth <token>' \
--header 'Content-Type: image/png' \
--form 'thumbnail=#"/C:/Users/user/Pictures/nami.PNG"'
However I have trouble translating that into js, what I did so far is:
// the "file" is the File from <input type="file"> - data on this looks ok
uploadThumbnail async (file) {
const formData = new FromData();
const formData.append('thumbnail', file, 'test.png');
await fetch.post('https://www.googleapis.com/youtube/v3/thumbnails/set', {
headers: {
Authorization: 'Oauth <token>',
'Content-Type': 'multipart/form-data' // I also tried using the file.type here (image/png)
},
query: {
videoId: <video id>
},
body: formData,
})
}
(to simplify the logic, I only manually typed the code above, so pardon if there are any typo.)
but this throws The request does not include the image content. I don't understand, I also tried converting the File into Blob, but same error.
As pointed out on the comments on my main post, I combined the answers and came up with this (this works!)
await fetch.post(`https://www.googleapis.com/upload/youtube/v3/thumbnails/set?videoId=${videoId}&uploadType=media`, {
headers: {
Authorization: 'Bearer <token>',
'Content-Type': file.type
},
body: file,
})
Mistakes are:
My endpoint is wrong and is missing uploads (this API is different from other youtube endpoints, so if you are reusing a variable base_url better check it out.
Using Oauth instead of Bearer.
There are no query in fetch
No need to convert and add the formData, pass the file directly instead.

data-Binary in request nodejs

I'm trying to upload a file to dropbox throug nodeJS.
This CURL request works.
curl -X POST https://content.dropboxapi.com/2/files/upload \
--header "Authorization: Bearer myToken" \
--header "Dropbox-API-Arg: {\"path\": \"/Homework/math/Matrices.txt\",\"mode\": \"add\",\"autorename\": true,\"mute\": false}" \
--header "Content-Type: application/octet-stream" \
--data-binary #fileName
I don't know how to translate it into javascript code.
Here's what I've accomplished so far:
var request = require('request')
var headers = {
"Authorization": "Bearer " + dropboxToken,
"Dropbox-API-Arg": {
"path": "/"+fileName, //nome sul drive
"mode": "add",
"autorename": true,
"mute": false
},
"Content-Type": "application/octet-stream"
}
var options = {
url: 'https://content.dropboxapi.com/2/files/upload',
method: 'POST',
headers: headers,
}
request(options, function (error, response, body) {
if (!error && response.statusCode == 200) {
console.log(body)
}
});
How do I include the data-binary option in this request in order to select the file to upload?
Thanks.
you can create a readstream and then pipe it to request with your current headers and options like-
fs.createReadStream('/path/to/youfile').pipe(request.post(options).on('end', (done) => { console.log('success') }));
First, if you're trying to integrate with the Dropbox API in JavaScript, we recommend using the official Dropbox API v2 JavaScript SDK, as it will do most of the work for you:
https://github.com/dropbox/dropbox-sdk-js
Otherwise, if you don't want to use the SDK, you can make the requests yourself. In this case, the --data-binary parameter is the curl parameter for supplying the data for the request to curl. curl then takes that data and puts it in the request body, which is the correct way to supply file data for a Dropbox API v2 "content-upload" style endpoint, such as /2/files/upload.
So, you should check the documentation for the HTTP client you're using for information on how to set the request body. It looks like you're using the request node module, which appears to take a body option, where you can put the request data.

JQuery $.post() and curl

This is what the GroupMe API (https://dev.groupme.com/docs/v3#messages_create) asks for:
$ curl -X POST -H "Content-Type: application/json" -d '{"source_guid": "frgfre", "text":"alala"}' https://api.groupme.com/v3/groups/ID/messages?token=YOUR_ACCESS_TOKEN
Please assume ID is a valid group id and the token is also valid and works. How exactly would I convert that to a $.post() request and run it from the console of a browser? Here is what I have that is not working in IE when Cross Domain is enabled and it is a trusted site:
var t = {"source_guid": "frgfre", "text":"alala"};
$.post("https://api.groupme.com/v3/groups/ID/messages?token=YOUR_ACCESS_TOKEN", t);
//I have also tried t.toString() as well but it didn't work
If that can't be converted (or what I have right now is correct), where would I run the first bit of code?
$.post posts the data in application/x-www-form-urlencoded format. If the API requires it to be JSON, you need to use $.ajax to override the default.
$.ajax({
url: "https://api.groupme.com/v3/groups/ID/messages?token=YOUR_ACCESS_TOKEN",
data: JSON.stringify(t),
contentType: 'application/json',
processData: false
});

Upload Base64 Video to Parse.com - Javascript

I'm trying to get my base64 video data to save to Parse.com. I'm using the same technique for images and it works fine, but video will not save for some reason. I've have been trying to debug this issue for weeks with no success. I basically copied the technique/code after I had images working this way... using base64 I figured it would be more or less work the same...
My video data looks like this:
data:video/3gpp;base64,AAAAGGZ0eXAzZ3A0AAAAAGlzb2.....
The video being saved is only ~56kb - ~1mb. Saving to Parse.com which has a 10mb file limit. I've checked my data and everything seems right, right up until I try to save the file to Parse.com, which spits back an error 400.
POST https://api.parse.com/1/files/myVideo.3gp 400 (Bad Request)
along with this in my XHR Response :
{"code":107,"error":"base64 field cannot be decoded"}
Anyone have any insight as to why it may not be working:
var videoFile = new Parse.File('myVideo.3gp', {
base64: _params.videoData
});
// save the parse file
videoFile
.save({
success: function(resp) {
window.ERROR = "Success: " + resp;
},
error: function(e, r) {
window.ERROR = "Error: " + e + " : " + r;
}
})
.then(function() {
_params.videoData = null;
// create object to hold caption and file reference
var videoObject = new ImageObject();
// set object properties
videoObject.set('title', _params.title);
videoObject.set('user', Parse.User.current());
videoObject.set('img', videoFile);
if (_params.location !== undefined) {
videoObject.set('location', new Parse.GeoPoint(_params.location.latitude, _params.location.longitude));
}
// save object to parse backend
videoObject
.save()
.then(function(resp) {
console.log('Posted Video', resp);
// Add User QtdPhoto
defer.resolve(resp);
});
}, function(error) {
console.log('Error', error);
defer.reject(error);
});
HTTP Status code 400 means that your request is not formed correctly. Can you copy-paste the actual HTTP request that is being made from DevTools or Firebug.
On the other note, if the request is being cut off after exactly the same amount of length. It may be caused by a firewall/router on your side of the equation. Are you behind a corporate network?
UPDATE:
As a response to author's comment. There are 2 ways to save file to Parse.com:
Using REST API
Using simple HTTP POST request
First method
I prefer using HTML5 file field to handle the file for me. It allows users to choose a file.
var videoFile = document.getElementById("your-file");
if (videoFile.files.length > 0) {
var parseFile = new Parse.File("myVideo.3gp", videoFile.files[0]);
}
parseFile.save().then(function() {
// Success
}, function(error) {
// Error: alert() or log()
console.log(error);
});
<input id="your-file" type="file" />
Second method:
Make a POST request like so or read the docs here.
curl -X POST \
-H "X-Parse-Application-Id: ${APPLICATION_ID}" \
-H "X-Parse-REST-API-Key: ${REST_API_KEY}" \
-H "Content-Type: video/3gp" \
--data-binary '#your-local-file.3gp' \
https://api.parse.com/1/files/videoFile.3gp
Just do the equivalent of this curl in your AJAX request. Is coding in native environment an option? Or, are you coding for PhoneGap, Ionic, etc.?

Using Netbanx API

I'm trying to use the Netbanx API and i always get {"error":{"code":401,"message":"Not authorised"}} I dont know what I am doing wrong.
var url = "https://api.test.netbanx.com/hosted/v1/orders";
$.ajax({
url: url,
headers: {
"Authorization": "Basic " + btoa("devcentre4157:B-qa2-0-54b6431d-302c021451aabe02869ba82a4a4253d8b2a170d7950d228b021448948677e24be8180f945f1af2b583676c353b9f")
},
type: 'POST',
dataType: 'jsonp',
contentType: 'application/json',
data: "{merchantRefNum:'89983943',currencyCode:'CAD',totalAmount:'10'}",
success: function (data) {
alert(JSON.stringify(data));
},
error: function (err) {
console.log(err);
}
});
I verified your code in and receive 401 as well.
Credentials is good, I did curl request and it's return data
curl -X POST -H "Content-Type: application/json" \
-u devcentre4157:B-qa2-0-54b6431d-302c021451aabe02869ba82a4a4253d8b2a170d7950d228b021448948677e24be8180f945f1af2b583676c353b9f \
https://api.test.netbanx.com/hosted/v1/orders \
-d '{
"merchantRefNum" : "89983943",
"currencyCode" : "CAD",
"totalAmount" : 10
}'
{"currencyCode":"CAD","id":"27HBQC4JI28QISA1LM","link":[{"rel":"hosted_payment","uri":"https://pay.test.netbanx.com/hosted/v1/payment/53616c7465645f5f9d3670f3f61d1664e3c0db218618a55369145e7577df013ab0691c526e56a445"},{"rel":"self","uri":"https://devcentre4157:B-qa2-0-54b6431d-302c021451aabe02869ba82a4a4253d8b2a170d7950d228b021448948677e24be8180f945f1af2b583676c353b9f#api.test.netbanx.com/hosted/v1/orders/27HBQC4JI28QISA1LM"},{"rel":"resend_callback","uri":"https://devcentre4157:B-qa2-0-54b6431d-302c021451aabe02869ba82a4a4253d8b2a170d7950d228b021448948677e24be8180f945f1af2b583676c353b9f#api.test.netbanx.com/hosted/v1/orders/27HBQC4JI28QISA1LM/resend_callback"}],"merchantRefNum":"89983943","mode":"live","totalAmount":10,"type":"order"}
I used DHC chrome plugin for one more check - it works as well. SO I am pretty sure there is Cross Domain problem with your JavaScript example. Netbanx just does not allow to do Cross Domain request to API.
Normally in these situations the issue is how the key is encoded. it is posisble that when copying and pasting there are spaces at the beginning or end. The credentials do look valid.

Categories

Resources