Image upload to facebook from clientside using FormData() - what's wrong? - javascript

On input file change event, I am executing the following code.
create a form data by encoding the image to "multipart/form-data"
alert('before calling FB.api-post :' + imgFile.name) - this works
create the param to be used in FB.api
call FB.api - but this never
gets executed. - what's wrong ?
var fData = new FormData();
var imgFile = $('input[type="file"]')[0].files[0];
fData.append("image", imgFile);
alert('before calling FB.api-post :' + imgFile.name);
var params = {
"access_token": $D("access_token"),
"message": $D("img_message"),
"upload file": true,
"source":fData
}
FB.api('/me/photos', 'POST', params,
function (response) {
alert('asasasasasasasasasasasasas');
if (!response || response.error) {
$D("preview").innerHTML = "Error in facebook Photo UPLOAD : " + response.error;
alert('Error in facebook Photo UPLOAD : ' + response.error);
}
else {
$D("preview").innerHTML = "Photo UPLOADED : " + response;
alert('uploaded');
}
}
);
});
Note: $D is nothing but the following shortcut
function $D(element) {
return document.getElementById(element);
}

Related

While uploading multiple input files to the document library, Ajax executes after the loop ends in jQuery

I'm having a problem when using the jQuery .each() and .ajax() functions together when i want to upload all input file to SharePoint document library .
function checkAttachments(NewlyCreatedItemId)
{
$("[type='file']").each(function(){
var FileUploaderID=$(this).attr("id");
var attachfor=$(this).attr("alt");
var file = document.getElementById(FileUploaderID.toString()).files[0];
if (file != undefined) {
uploadDocument(FileUploaderID,attachfor,NewlyCreatedItemId);
}
else {
alert('Please, upload attachments for ');
}
});
}
function uploadDocument(uploader,attachfor,createdID) {
var files = $("#"+uploader+"")[0].files;
if (files.length > 0) {
var fileName = files[0].name;
var webUrl = _spPageContextInfo.webAbsoluteUrl;
var documentLibrary = "ClaimAttachments";
var targetUrl = _spPageContextInfo.webServerRelativeUrl + "/" + documentLibrary;
// Construct the Endpoint
var url = webUrl + "/_api/Web/GetFolderByServerRelativeUrl(#target)/Files/add(overwrite=true, url='" + fileName + "')?#target='" + targetUrl + "'&$expand=ListItemAllFields";
uploadFileToFolder(files[0], url, function(data) {
var file = data.d;
var DocFileName = file.Name;
var updateObject = {
__metadata: {
type: file.ListItemAllFields.__metadata.type
},
FileLeafRef: DocFileName , //FileLeafRef --> Internal Name for Name Column
AttachFor : attachfor ,
RequestGUID : createdID
};
alert("File uploaded successfully!");
}, function(data) {
alert("File uploading failed");
});
} else {
alert("Kindly select a file to upload.!");
}
}
function getFileBuffer(uploadFile) {
var deferred = jQuery.Deferred();
var reader = new FileReader();
reader.onloadend = function(e) {
deferred.resolve(e.target.result);
}
reader.onerror = function(e) {
deferred.reject(e.target.error);
}
reader.readAsArrayBuffer(uploadFile);
return deferred.promise();
}
function uploadFileToFolder(fileObj, url, success, failure) {
var apiUrl = url;
// Initiate method calls using jQuery promises.
// Get the local file as an array buffer.
var getFile = getFileBuffer(fileObj);
// Add the file to the SharePoint folder.
getFile.done(function(arrayBuffer) {
$.ajax({
url: apiUrl,//File Collection Endpoint
type: "POST",
data: arrayBuffer,
processData: false,
async: false,
headers: {
"accept": "application/json;odata=verbose",
"X-RequestDigest": jQuery("#__REQUESTDIGEST").val(),
},
success: function(data) {
success(data);
},
error: function(data) {
success(data);
}
});
});
}
it uploads the file of the first file uploader only because when it reach to the ajax call in function (uploadFileToFolder) go to the next iteration, how to can solve it .

How to handle multiple file upload using same js function - jquery

Need to make the file upload function upload multiple files at a go. The file upload works fine if uploading just ONE file at a time and upload is done in chunk...
Right now, there is need to expand the form capability to allow multiple file fields which allow user to make multiple selection of files and handling this using a loop within the js function. I tried but it isn't working for me. Not been able to get the js function to work with selection of multiple files. When more than one file is uploaded, it conflicts with each other and none of the file get uploaded successfully.
(function($) {
var fileReader = {};
var file = {};
var slice_size = 1000 * 1024;
function triggerUpload(event) {
event.preventDefault();
fileReader = new FileReader();
file = document.querySelector('#my_file_upload').files[0];
fileUploadHandler(0);
}
$('#form_upload_submit').on('click', triggerUpload);
function fileUploadHandler(start) {
var next_slice = start + slice_size + 1;
var blob = file.slice(start, next_slice);
fileReader.onloadend = function(event) {
if (event.target.readyState !== FileReader.DONE) {
return;
}
var form_data = {
file_data: event.target.result,
file: file.name,
file_type: file.type
};
$.ajax({
url: "server_upload.php",
type: 'POST',
dataType: 'json',
cache: false,
data: form_data,
error: function(jqXHR, textStatus, errorThrown) {
alert('Upload failed');
},
success: function(data) {
alert('success : ' + file.name);
var size_done = start + slice_size;
var percent_done = Math.floor((size_done / file.size) * 100);
if (next_slice < file.size) {
$('#progress_display').html(percent_done + '% Uploaded');
fileUploadHandler(next_slice);
} else {
$('#progress_display').html('Upload Completed!');
}
}
});
};
fileReader.readAsDataURL(blob);
}
})(jQuery);
<?php
$upload_dir = '../upl/';
$file_path = $upload_dir . $_POST['file'];
$file_data = decodeFile( $_POST['file_data'] );
file_put_contents( $file_path, $file_data, FILE_APPEND );
function decodeFile($data)
{
$data = explode( ';base64,', $data );
$data = base64_decode( $data[1] );
return $data;
}
?>
Would be pleased to get some help with this. Thanks!

IF statement to check if file exists in path not working

I am trying to check if a file from a multiple upload exists in the path already, if so i want to chuck out a validation error. Its the else if part that is not working. The number directory gets created in the ajax controller server side, but i want to do a check before they upload further files with the same name to that directory. Is this possible? What am i doing wrong here?
function makeProgress(number){
var url = getRelativeURL("web/fileUpload");
var formData = new FormData();
formData.append('number', number);
fls = document.getElementById("attachmentFileUploadInput").files; //number of files...
console.log(fls);
var location = "C:/temp/" + number + "/";
console.log(location);
// maximum number of files at a time is 10
if(fls.length >= 11){
FileUploadLengthVisible(true);
return false;
}
var j;
for(j=0;j<fls.length;j++){
if (fls[j].size > 5000000) //5MB size per file
{
FileUploadSizeVisible(true);
return false;
}
else if (location + fls[j] == true)
{
alert("file exists");
return false;
}
else
{
formData.append('files[]', fls[j]); //note files[] not files
$.ajax({
url : url,
data : formData,
processData : false,
cache: false,
contentType: false,
type : 'POST',
success : function(data) {
FileUploadVisible(true);
$('#attachmentModal').modal('hide')
$(':input','#attachmentModal').val("");
$("#pbarmain").hide();
$("#pbar").hide();
$("#actionPlanDiv").hide();
setObjectEnabled('#Upload',false);
},
error : function(err) {
FileUploadErrorVisible(true);
}
});
console.log('loop each file working');
}
}
console.log("form data " + formData);
}

Link not opening after streaming data of the document down

I think I am missing some code on the JavaScript side. I am downloading the documents for each request. When the user clicks on the link, I go get the document data and stream it down. I see on Fiddler that the data is coming down, but the .txt document link is not opening.
[HttpGet]
public HttpResponseMessage GetDataFiles(Int64 Id)
{
var results = context.PT_MVC_RequestFile.Where(x => x.RowId == Id).FirstOrDefault();
HttpResponseMessage response = new HttpResponseMessage(HttpStatusCode.OK);
try
{
if (results != null)
{
response.Headers.AcceptRanges.Add("bytes");
response.StatusCode = HttpStatusCode.OK;
response.Content = new ByteArrayContent(results.Data);
response.Content.Headers.ContentDisposition = new ContentDispositionHeaderValue("attachment");
response.Content.Headers.ContentDisposition.FileName = results.FileName;
response.Content.Headers.ContentType = new MediaTypeHeaderValue("application/octet-stream");
response.Content.Headers.ContentLength = results.Data.Length;
}
}
catch (EntityException ex)
{
throw new EntityException("GetFiles Failed" + ex.Message);
}
return response;
}
Firstly, I downloaded all the documents for that request, and if the user clicks on the file, I call the download stream action.
$.ajax({
url: url,
type: 'GET',
// data: JSON.stringify(model, null),
contentType: "application/json",
success: function (data) {
if (data != "") {
$("#fileLength").val(data.length);
// alert(data.length);
$.each(data, function (i, item) {
var newDiv = $(document.createElement('div')).attr("id", 'file' + i);
newDiv.html("<input id=\"cb" + i + "\" type=\"checkbox\"> <a href=\"#\" onclick=\"GetData('" + item.RowId + "','" + item.mineType + "')\" >" + item.FileName + "</a>");
newDiv.appendTo("#fileRows");
});
} else {
}
},
error: function (xhr, ajaxOptions, thrownError) {
}
});
I think I am missing something after success though. Somehow it downloads the data, but the link does not open. Could it be the content type is not set, or that it thinks it is JSON data? Help with some ideas please.
Here is the link:
function GetData(rowId,mineType) {
// alert(mineType);
var url = "api/MyItemsApi/GetDataFiles/" + rowId;
$.ajax({
url: url,
type: 'GET',
//data: JSON.stringify(model, null),
contentType: "application/json",
success: function (data) {
},
error: function (xhr, ajaxOptions, thrownError) {
}
});
}
You can't easily download a file through an Ajax request. I recommend to post the data to a blank page from a form, instead of the Ajax (you can populate that form and post it via jQuery if you need to). If you're interested, I could guide you through it, just let me know.
If you still want to download from Ajax, I suggest you refer to this post.

How to get uploaded images from Parse using javascript API

Problem:
I have the Url (eg. http://files.parse.com/../../..jpg ) of the uploaded file and it's fileName, and now need to retrieve the corresponding file from that Url(Parse.com) by using Only via Javascript . Any one have the answer let me know. Thank you very much!
Code: (upload):
function uploadFn(fileName,fileType,fileData,c){
var parseUrl='https://api.parse.com/1/files/'+fileName;
$.ajax({
type:'post',
beforeSend:function(req){
req.setRequestHeader('X-Parse-Application-Id',myParseAppId);
req.setRequestHeader('X-Parse-REST-API-Key',myParseRestApiId);
req.setRequestHeader('Content-Type',fileType); // fileType always == 'image/jpg;'
},
url:parseUrl,
data:fileData,
processData:false,
contentType:false,
success:function(rslt){
if(rslt){
alert('Upload success\n Filename:'+rslt.name+'\n Url:'+rslt.url);
imgObj.save({curUser:curUser,fileName:rslt.name,fileUrl:rslt.url,fileId:c},
{success:function(succ){
alert('File info saved!');
},error:function(err){
alert('Error:'+err.code);
}
}) // save
}
},
error:function(err){
//var errObj=jQuery.parseJSON(err);
alert('Error:'+err.responseText);
}
});
}
upload is not a problem. It works fine! Only for retrieving from Parse.com
(toRetrieve) [I tried as: ]
function fetchImg(url){
$.ajax({
url:url,
async:false,
type:'POST',
beforeSend:function(req){
req.setRequestHeader('X-Parse-Application-Id',myParseAppId);
req.setRequestHeader('X-Parse-REST-API-Key',myParseRestApiId);
req.setRequestHeader('Content-Type','image/jpg');
},
complete:function(rslt){
$('#imgId').attr('src','data:image/jpg;base64,'+rslt.responseText);
},
success:function(){//Success
},
error:function(err){
alert('Error: '+err.responseText+'\nStatus: '+err.statusText);
}
})
}
[output:]
'Error-msg>The specified method not allowed against this resouce' Status: Method Not allowed!.
Notes: ¤ (I saved the fileName, fileUrl to the Parse DataBrowser, and used this for try to retrieve the uploaded file.)
¤ (App is based on 'Phonegap')
¤ Im novice to Parse/Javascript.
Thanks a lot! *
Check here: Load contents of image from camera to a file
basically: with the info in this post. . Big thanks to Raymond Camden!
function gotPic(data) {
window.resolveLocalFileSystemURI(data, function(entry) {
var reader = new FileReader();
reader.onloadend = function(evt) {
var byteArray = new Uint8Array(evt.target.result);
var output = new Array( byteArray.length );
var i = 0;
var n = output.length;
while( i < n ) {
output[i] = byteArray[i];
i++;
}
var parseFile = new Parse.File("mypic.jpg", output);
parseFile.save().then(function(ob) {
navigator.notification.alert("Got it!", null);
console.log(JSON.stringify(ob));
}, function(error) {
console.log("Error");
console.log(error);
});
}
reader.onerror = function(evt) {
console.log('read error');
console.log(JSON.stringify(evt));
}
entry.file(function(s) {
reader.readAsArrayBuffer(s);
}, function(e) {
console.log('ee');
});
});
}
I think to retrieve the image method should be GET instead of POST for your ajax request.

Categories

Resources