Upload image to facebook from input file - javascript

So, i'm trying top upload a simple image to facebook using the graph api.
The file is uploaded by an input type file
var file= $("#imagenesUpload")[0].files[0];
var formData = new FormData();
formData.append("source", file);
FB.api("/me/photos", "POST", formData,
function (response) {
if (response) {
console.log(response);
}
}
);
But i'm always getting a (#324) Requires upload file
Also tried this with the same result
var file= $("#imagenesUpload")[0].files[0];
FB.api("/me/photos", "POST", {"source":file},
function (response) {
if (response) {
console.log(response);
}
}
);

On the official Facebook Developers site there is a post explaining how images should be set. Here is the link: https://developers.facebook.com/blog/post/498/
(Check out Scenario 2)

Related

Get .wav blob from url

I'm trying to get a blob from an URL (in my case leads to a .wav file).
The URL is located at my own website, so I only do requests to the same site.
The purpose:
A user has uploaded some .wav files to my website to one schema
The user wants to copy one or more .wav files from one to another schema
The user selects the audiofiles to copy without uploading the files again.
The user interface looks like this:
The problem:
Each audiofile is located in its own directory.
https://mywebsite.nl/media/audiofiles/schemaGUID/recording.wav
So when copying to another schema, the file or files needs to get re-uploaded to the directory of the other schema.
The code im using to upload the selected audiofiles is this:
newwavfiles.forEach(function (item) {
var name = item["name"];
var filename = item["filename"];
var fileblob = fetch('http://mywebsite.nl/media/audiofiles/12345677/recording.wav').then(res => res.blob());
var formData = new FormData();
formData.append('file', fileblob, filename);
formData.append('guid', guid);
// upload file to server
$.ajax({
url: 'index.php?action=uploadAudiofile',
type: 'post',
data: formData,
enctype: 'multipart/form-data',
contentType: false,
processData: false,
success: function (response) {
},
error: function (xhr, status, error) {
console.log(xhr);
var errorMessage = xhr.status + ': ' + xhr.statusText
}
});
});
To get the blob of the file I tried this:
var fileblob = fetch('http://mywebsite.nl/media/audiofiles/12345677/recording.wav').then(res => res.blob());
But then I get this error:
Failed to execute 'append' on 'FormData': parameter 2 is not of type 'Blob'.
Does anyone have a solution to get the .wav file blob from an URL?

Facebook Graph API publish picture with Javascript

I'm using the Facebook Javascript SDK in my react app and I want to make a post with multiple photos. I know that that means I have to first post the pictures unpublished and then use the returned ids to make the post.
However, I'm having trouble finding good documentation and running into issues figuring out how to allow a user select and post a local picture (not from a url). The code is a bit difficult to put all here, but here are the steps I'm taking and the errors I'm getting:
Get file the user selected using a file input.
Encode the picture as a blob and put that and the access token into FormData to use in the api request.
var reader = new FileReader();
reader.onload = function(e) {
var arrayBuffer = e.target.result;
var blob = new Blob([arrayBuffer], { type: photo.type });
var pictureData = new FormData();
pictureData.append('access_token:', this.state.FBaccessToken);
pictureData.append('source', blob);
return pictureData;
}.bind(this)
return reader.readAsArrayBuffer(photo);
Do a post request
var encodedRequest = this.encodePhoto(photo);
FB.api(
"/me/photos?published=false",
"POST",
encodedRequest,
function (response) {
if (response && !response.error) {
//once successfully gotten the photos add them to the array of photo ids
temp.push({"media_fbid": response.id});
console.log(response);
}
else {
alert(response.error.message);
}
}.bind(this)
);
The error when I run it this way is that it doesn't seem to recognize the access token, but when I remove the access token from pictureData in step 2, and change the api encodedRequest part to this:
{
access_token: this.state.FBaccessToken,
source: encodedRequest,
},
I get the error "(#324) Requires upload file". I tried adding fileUpload: true, to the SDK init code but that also didn't seem to do anything. Posting simple text only statuses and reading from feed is all working fine.
Sorry for the long post, but I'd be really grateful if anyone has any insight! Thanks.
Is it the extra colon you have after access_token in your first pictureData.append() call?
pictureData.append('access_token:', this.state.FBaccessToken);
versus
pictureData.append('access_token', this.state.FBaccessToken);
Edit: Below is output from postman to post images referencing a file on my laptop
var form = new FormData();
form.append("source", "/Users/patricklambe/images/test.jpg");
form.append("access_token", "PAGEACCESSTOKEN");
form.append("caption", "check this photo");
var settings = {
"async": true,
"crossDomain": true,
"url": "https://graph.facebook.com/v2.11/444873272561515/photos",
"method": "POST",
"headers": {
"cache-control": "no-cache",
"postman-token": "1d786fec-c9b1-2494-1b5c-8fd0e2ea5ade"
},
"processData": false,
"contentType": false,
"mimeType": "multipart/form-data",
"data": form
}
$.ajax(settings).done(function (response) {
console.log(response);
});

Trying to POST multipart/form-data by javascript to web api

Here i have a form in which i have a input type file to upload my file when the upload button is click i need to post the multipart/form-data to web api
where i upload the file to Minio Server.I have pasted the javascript and web api i use below.
When i press upload button after i get 500 (Internal Server Error).Help me with suggestions.
$("#upload").click(function () {
var file = new FormData($('#uploadform')[0]);
file.append('tax_file', $('input[type=file]')[0].files[0]);
$.ajax({
type: "POST",
url: 'http://localhost:53094/api/values',
data: file,
//use contentType, processData for sure.
contentType: "multipart/form-data",
processData: false,
beforeSend: function () {},
success: function (msg) {
$(".modal .ajax_data").html("<pre>" + msg +
"</pre>");
$('#close').hide();
},
error: function () {
$(".modal .ajax_data").html(
"<pre>Sorry! Couldn't process your request.</pre>"
);
$('#done').hide();
}
});
});
[HttpPost]
public string Post(IFormFile file)
{
try
{
var stream = file.OpenReadStream();
var name = file.FileName;
minio.PutObjectAsync("student-maarklist", "sample.jpeg", stream, file.Length);
return "Success";
}
catch (Exception ex)
{
return ex.Message;
}
}
I think you need not mention localhost just the path to the file will do. or replace it with IP of the localhost.
Sorry i have dont a mistake the name i appended in javascript is not save as the name i gave in web api.
I changed,
file.append('tax_file', $('input[type=file]')[0].files[0]);
To
file.append('file', $('input[type=file]')[0].files[0]);
and it worked .

Upload files to Dropbox using a Dropbox Core API in Javascript

I am working on a simple chrome-extension that needs to upload files to the user's dropbox folder. I am using the simple AJAX requests as mentioned below to upload files, however it works for files with extensions such as .txt, .json, .c, etc i.e. files whose mime type is of type text/plain or similar type but all other file types such as pdfs, image files etc get corrupted and produce blank contents. What am I missing in uploading the files the correct way.
function startUpload()
{
var folderPath = $(this).closest('tr').attr('path')+'/';
var file = $("#upload_file")[0].files[0];
if (!file){
alert ("No file selected to upload.");
return false;
}
var reader = new FileReader();
reader.readAsText(file, "UTF-8");
reader.onload = function (evt) {
uploadFile(folderPath+file.name,evt.target.result,file.size,file.type);
}
}
//function to upload file to folder
function uploadFile(filepath,data,contentLength,contentType){
var url = "https://api-content.dropbox.com/1/files_put/auto"+filepath;
var headers = {
Authorization: 'Bearer ' + getAccessToken(),
contentLength: contentLength,
};
var args = {
url: url,
headers: headers,
crossDomain: true,
crossOrigin: true,
type: 'PUT',
contentType: contentType,
data : data,
dataType: 'json',
success: function(data)
{
getMetadata(filepath.substring(0,filepath.lastIndexOf('/')),createFolderViews);
},
error: function(jqXHR)
{
console.log(jqXHR);
}
};
$.ajax(args);
}
I believe the issue is reader.readAsTextFile(file, "UTF-8"). If the file isn't a text file, this will misinterpret the contents. I think you want reader.readAsBinaryString or reader.readAsArrayBuffer. (I haven't tested it myself.)
EDIT
After testing this myself, I found that readAsArrayBuffer is what you need, but you also need to add processData: false as an option to $.ajax to prevent jQuery from trying to convert the data to fields in a form submission.
Also be sure to use dataType: 'json' to properly parse the response from the server.

File Upload without Form

Without using any forms whatsoever, can I just send a file/files from <input type="file"> to 'upload.php' using POST method using jQuery. The input tag is not inside any form tag. It stands individually. So I don't want to use jQuery plugins like 'ajaxForm' or 'ajaxSubmit'.
You can use FormData to submit your data by a POST request. Here is a simple example:
var myFormData = new FormData();
myFormData.append('pictureFile', pictureInput.files[0]);
$.ajax({
url: 'upload.php',
type: 'POST',
processData: false, // important
contentType: false, // important
dataType : 'json',
data: myFormData
});
You don't have to use a form to make an ajax request, as long as you know your request setting (like url, method and parameters data).
All answers here are still using the FormData API. It is like a "multipart/form-data" upload without a form. You can also upload the file directly as content inside the body of the POST request using xmlHttpRequest like this:
var xmlHttpRequest = new XMLHttpRequest();
var file = ...file handle...
var fileName = ...file name...
var target = ...target...
var mimeType = ...mime type...
xmlHttpRequest.open('POST', target, true);
xmlHttpRequest.setRequestHeader('Content-Type', mimeType);
xmlHttpRequest.setRequestHeader('Content-Disposition', 'attachment; filename="' + fileName + '"');
xmlHttpRequest.send(file);
Content-Type and Content-Disposition headers are used for explaining what we are sending (mime-type and file name).
I posted similar answer also here.
UPDATE (January 2023):
You can also use the Fetch API to upload a file directly as binary content (as also was suggested in the comments).
const file = ...file handle...
const fileName = ...file name...
const target = ...target...
const mimeType = ...mime type...
const promise = fetch(target, {
method: 'POST',
body: file,
headers: {
'Content-Type': mimeType,
'Content-Disposition', `attachment; filename="${fileName}"`,
},
},
});
promise.then(
(response) => { /*...do something with response*/ },
(error) => { /*...handle error*/ },
);
See also a related question here: https://stackoverflow.com/a/48568899/1697459
Step 1: Create HTML Page where to place the HTML Code.
Step 2: In the HTML Code Page Bottom(footer)Create Javascript: and put Jquery Code in Script tag.
Step 3: Create PHP File and php code copy past. after Jquery Code in $.ajax Code url apply which one on your php file name.
JS
//$(document).on("change", "#avatar", function() { // If you want to upload without a submit button
$(document).on("click", "#upload", function() {
var file_data = $("#avatar").prop("files")[0]; // Getting the properties of file from file field
var form_data = new FormData(); // Creating object of FormData class
form_data.append("file", file_data) // Appending parameter named file with properties of file_field to form_data
form_data.append("user_id", 123) // Adding extra parameters to form_data
$.ajax({
url: "/upload_avatar", // Upload Script
dataType: 'script',
cache: false,
contentType: false,
processData: false,
data: form_data, // Setting the data attribute of ajax with file_data
type: 'post',
success: function(data) {
// Do something after Ajax completes
}
});
});
HTML
<input id="avatar" type="file" name="avatar" />
<button id="upload" value="Upload" />
Php
print_r($_FILES);
print_r($_POST);
Basing on this tutorial, here a very basic way to do that:
$('your_trigger_element_selector').on('click', function(){
var data = new FormData();
data.append('input_file_name', $('your_file_input_selector').prop('files')[0]);
// append other variables to data if you want: data.append('field_name_x', field_value_x);
$.ajax({
type: 'POST',
processData: false, // important
contentType: false, // important
data: data,
url: your_ajax_path,
dataType : 'json',
// in PHP you can call and process file in the same way as if it was submitted from a form:
// $_FILES['input_file_name']
success: function(jsonData){
...
}
...
});
});
Don't forget to add proper error handling
Try this puglin simpleUpload, no need form
Html:
<input type="file" name="arquivo" id="simpleUpload" multiple >
<button type="button" id="enviar">Enviar</button>
Javascript:
$('#simpleUpload').simpleUpload({
url: 'upload.php',
trigger: '#enviar',
success: function(data){
alert('Envio com sucesso');
}
});
A non-jquery (React) version:
JS:
function fileInputUpload(e){
let formData = new FormData();
formData.append(e.target.name, e.target.files[0]);
let response = await fetch('/api/upload', {
method: 'POST',
body: formData
});
let result = await response.json();
console.log(result.message);
}
HTML/JSX:
<input type='file' name='fileInput' onChange={(e) => this.fileInput(e)} />
You might not want to use onChange, but you can attach the uploading part to any another function.
Sorry for being that guy but AngularJS offers a simple and elegant solution.
Here is the code I use:
ngApp.controller('ngController', ['$upload',
function($upload) {
$scope.Upload = function($files, index) {
for (var i = 0; i < $files.length; i++) {
var file = $files[i];
$scope.upload = $upload.upload({
file: file,
url: '/File/Upload',
data: {
id: 1 //some data you want to send along with the file,
name: 'ABC' //some data you want to send along with the file,
},
}).progress(function(evt) {
}).success(function(data, status, headers, config) {
alert('Upload done');
}
})
.error(function(message) {
alert('Upload failed');
});
}
};
}]);
.Hidden {
display: none
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.0/jquery.min.js"></script>
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.2.23/angular.min.js"></script>
<div data-ng-controller="ngController">
<input type="button" value="Browse" onclick="$(this).next().click();" />
<input type="file" ng-file-select="Upload($files, 1)" class="Hidden" />
</div>
On the server side I have an MVC controller with an action the saves the files uploaded found in the Request.Files collection and returning a JsonResult.
If you use AngularJS try this out, if you don't... sorry mate :-)

Categories

Resources