How to get uploaded images from Parse using javascript API - javascript

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.

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!

How to do Image type validation in magento.?

I am new to magento. I just want to do image validation in magento but i am struggling alot. I used ajax validation but append() function in jquery is not supporting in magento, So i dont know how to do this.
My ajax code:
jQuery(function () {
var url = jQuery('#image_url').val();
var vendorImage = jQuery('#vendor_logo');
vendorImage.on("change", function () {
var fd = new FormData();
var file = jQuery('#vendor_logo')[0].files[0];
if (file) {
fd.append('vendor_logo', file);
}
jQuery.ajax({
url: url,
type: 'POST',
cache: false,
data: fd,
success: function (result) {
alert(0);
alert(result);
jQuery("#output").html("Upload success.");
}
});
});
});
I am getting error for append() function.
I think It would be better if i use add rule in validation.js file
My code here:
Validation.add('validate-imgtype', 'Please choos valid image', function(v) {
var Image = jQuery(v).val();
var extension = Image.split('.').pop().toUpperCase();
if (extension!="PNG" && extension!="JPG" && extension!="GIF" && extension!="JPEG"){
return extension;
}
});
But the above add rule code also not working.
Can anyone help me to resolve this???
Thanks in advance.
If you are asking for image validation in magento you can try doing
if($this->getRequest()->isPost())
{
if(isset($_FILES['myfileupload']['name']) and (file_exists($_FILES['myfileupload']['tmp_name'])))
{
$path = Mage::getBaseDir() . '/myfileupload';
if(!file_exists($path))
{ mkdir($path, 777, true); }
try {
$myfileupload = $_FILES['myfileupload']['name'];
$uploader = new Varien_File_Uploader('myfileupload');
$uploader->setAllowedExtensions(array('png', 'gif', 'jpeg', 'jpg', 'pdf'));
$uploader->setAllowCreateFolders(true);
$uploader->setAllowRenameFiles(false);
$uploader->setFilesDispersion(false);
$uploader->save($path, $myfileupload);
} catch (Exception $e) {
echo 'Error';
}
}
}

File not reaching till handler's method

<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.0.0/jquery.min.js"></script>
$(document).ready(function () {
$("#Button1").click(function (evt) {
var fileUpload = $('[id$=FileUpload1]')[0].value.split(",");
var data = new FormData();
for (var i = 0; i < fileUpload.length; i++) {
data.append(fileUpload[i].name, fileUpload[i]);
}
var options = {};
options.url = "Handler.ashx";
options.type = "POST";
options.data = data;
options.contentType = false;
options.processData = false;
options.success = function (result) { alert(result); };
options.error = function (err) { alert(err.statusText); };
$.ajax(options);
evt.preventDefault();
});
});
This was my jquery and below is my handler file code ......
till end i am getting value while debugging but in motto of making upload multiple images at a while i am unable to have any value in handle
handler code
public void ProcessRequest (HttpContext context) {
string filePath = "FileSave//";
foreach (string file in context.Request.Files)
{
HttpPostedFile filed = context.Request.Files[file];
filed.SaveAs(context.Server.MapPath(filePath + filed.FileName));
context.Response.Write("File uploaded");
}
}
You can try this way if you would like to.
$(document).ready(function () {
$("#Button1").click(function (evt) {
evt.preventDefault();
var formdata = new FormData();
var fileInput = $('#sliderFile'); //#sliderFile is the id of your file upload control
if ($(fileInput).get(0).files.length == 0)
{ //show error
return false;
}
else
{
$.each($(fileInput).get(0).files, function (index,value) {
formdata.append(value.name, value);
});
$.ajax({
url: 'Handler.ashx',
type: "POST",
dataType: 'json',
data: data,
processData: false,
contentType:false,
success: function (data) {
if (data.result) {
//return true or any thing you want to do here
}
else {
//return false and display error
}
},
error: function (data) {
//return false and display error
}
});
}
});//button click close
});//document.ready close
Try it and let me know
EDIT: Remember but, HTML5 FormData is not available in older browsers and your code will silently fail. If you need to support older browsers you might need to perform progressive enhancement by testing the capabilities of the browser and falling back to a standard form POST if the browser doesn't support FormData:
if(window.FormData === undefined) {
// The browser doesn't support uploading files with AJAX
// falling back to standard form upload
} else {
// The browser supports uploading files with AJAX =>
// we prevent the default form POST and use AJAX instead
e.preventDefault();
...
}
For more information on this you can see answer I have accepted for one of my questions. It's pretty much clear there what is the issue regarding. Here is the link
EDIT : Just adding these LINK1 and LINK2 for those who come looking for the answer.
use HttpContextBase[] instead of just HttpContext

How Do I Send The File Data Without Form With Ajax On Server?

I've coded a javascript code which nicely collects every file user wants to upload. But things turned when I added drag/drop file option.
By default, I had a code which monitored input[type='file'] change event handler and once it was detected, actions were performed and files were sent to server for upload.
But since drag/drop doesn't change the input[type='file'] value and neither I can change it programmatically due to security reasons, I'm struck how do I send files which are dragged and dropped on the site.
Here's some of my code:
document.getElementById('drop').addEventListener('drop', function (e) {
e = e || window.event;
e.preventDefault();
var dt = e.dataTransfer;
var files = dt.files;
for (var i=0; i<files.length; i++) {
var file = files[i];
var reader = new FileReader();
reader.readAsDataURL(file);
addEventHandler(reader, 'loadend', function(e, file) {
var bin = this.result;
var filename = file.name;
var filesize = (file.size/1048576).toFixed(2) + ' MB';
alert(' '+filename+' '+filesize+' '); // DEBUGGING ONLY
console.log("YEAY");
if(filecheck(filename)) { // Additional Function
step2(filesize, filename, bin); // Additional Function
$('.btn').click(function() { // Button to be clicked to start upload
$('#main_img_upload').submit(); // Form with that input[type='file']
});
}
else {
alert("Wrong File");
return false;
}
}.bindToEventHandler(file), false);
}
return false;
});
Obviously, it starts upload but server doesn't receive anything as no change has been made to form. But I have all the necessary details (name of file, size of file, etc..)
Any help would be appreciated.
Try out this code.
data.append("FileName", files[0]);
$.ajax({
url: "../",
type: "POST",
processData: false,
contentType: false,
data: data,
success: function (data) {
if (data) {
}
},
error: function (er) {
MSGBox(er);
}
});
}

Categories

Resources