uploading spreadsheet to parse.com from javascript - javascript

I am able to upload a spreadsheet (.csv or XLS files), but when checking on the file from Parse.com, it is all empty. I am uploading the file from client side code (not using REST). Do you think that is the problem? This works just fine for a simple image/file upload using a similar code, but fails for csv or xls type file.
Here's the code:
$scope.uploadSpFile = function(fileUpload){
var name = fileUpload.name;
var parseFile = new Parse.File(name, fileUpload.spFile);
var serverUrl = 'https://api.parse.com/1/files/' + fileUpload.name;
var mySpreadsheet = new Parse.Object(fileUpload.className);
$.ajax({
type: "POST",
beforeSend: function(request) {
request.setRequestHeader("X-Parse-Application-Id", parse_app_id);
request.setRequestHeader("X-Parse-REST-API-Key", parse_rest_id);
request.setRequestHeader("Content-Type", fileUpload.spFile.type);
},
url: serverUrl,
data: fileUpload.mySpreadsheet,
processData: false,
contentType: false,
success: function(data) {
mySpreadsheet.set({filetitle: data.name});
mySpreadsheet.set({fileurl: data.url});
mySpreadsheet.set({name: name});
mySpreadsheet.set({fileCategory: ''});
mySpreadsheet.set({file: {"name": data.name,"url": data.url,"__type": "File"}});
mySpreadsheet.save();
console.log('file saved!');
},
error: function(data) {
var obj = jQuery.parseJSON(data);
console.log('error: ' + obj.error);
outputMsg = obj.error;
}
});
}
});
when i use a similar code to upload an image, I can access the file on my parse page, but xls or csv files turn out to be empty (actually, in XLS case, an error pops out as the format is corrupted).
Anyone has any idea how to fix this issue?
thanks for the help.

Related

Uploading and handling images in SharePoint

I have a custom form on a SharePoint list in which the user uploads an image and a caption.
There is a PowerPoint slide with a template where the image should then go and the caption below it. Ideally I want the uploaded image to be taken from the SharePoint list and automatically input to the PowerPoint slide with the caption. The slide should then be saved as an image file and uploaded to SharePoint picture library to enable it to be used in a picture library slideshow on the homepage.
Does anyone have any idea how to do this or any other ways in which this may be possible.
I have tried using a combination of JavaScript and html with no luck.
You can use the SharePoint REST API to retrieve the image and caption from the SharePoint list, then use the Microsoft Graph API to add the image and caption to the PowerPoint slide template. Once the slide is updated, you can use the Microsoft Graph API to convert the slide to an image file and then upload the image file to the SharePoint picture library using the SharePoint REST API. You can use a programming language such as Python or JavaScript to automate this process.
You can refer to following code to upload pic to sharepoint by rest api and js
var fileInput = jQuery('#getFile');
var file = fileInput[0].files[0];
var serverRelativeUrlToFolder = '*****'; //if the library in subsite, You have to remove the forward slash "/" before the document library relative url.
proccessUploadUsingJQueryAjax(file, serverRelativeUrlToFolder);
function getFileBuffer(file) {
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(file);
return deferred.promise();
}
function addFileToFolderUsingJQueryAjax(fileName, arrayBuffer, serverRelativeUrlToFolder) {
// Construct the endpoint.
var fileCollectionEndpoint = String.format(
"{0}/_api/web/GetFolderByServerRelativeUrl('{1}')/files/add(overwrite=true, url='{2}')",
_spPageContextInfo.webAbsoluteUrl, serverRelativeUrlToFolder, fileName);
// Send the request and return the response.
// This call returns the SharePoint file.
return jQuery.ajax({
url: fileCollectionEndpoint,
type: "POST",
data: arrayBuffer,
processData: false,
contentType: "application/json;odata=verbose",
headers: {
"accept": "application/json;odata=verbose",
"X-RequestDigest": jQuery("#__REQUESTDIGEST").val()
}
});
}
function proccessUploadUsingJQueryAjax(file, serverRelativeUrlToFolder){
var getFile = getFileBuffer(file);
getFile.done(function (arrayBuffer) {
// Add the file to the SharePoint folder.
var addFile = addFileToFolderUsingJQueryAjax("image.jpg", arrayBuffer, serverRelativeUrlToFolder);
addFile.done(function (file, status, xhr) {
alert("File Uploaded");
});
addFile.fail(function (error) { alert("Error Add File: " + error.responseText); });
});
getFile.fail(function (error) { alert("Error Get File: " + error.responseText); });
}

Ajax Get Url is not Responding

I'm trying to get some XML file from the net and i need to display that in my html page......
This is how my javascript file looks like:
$(document).ready(function(){
$(".update").append("<ul></ul>");
$.ajax({
type: "GET",
url: "https://www2.informatik.hu-berlin.de/~xing/Lib/Docs/jaxp/docs/tutorial/sax/samples/slideSample01.xml",
dataType: "xml",
success: function(xml){
$(xml).find('slide').each(function(){
var sTitle = $(this).find('title').text();
//var sPublisher = $(this).find('heading').text();
$("<li></li>").html(sTitle + ", " + "sPublisher").appendTo(".update ul");
});
},
error: function() {
alert("An error occurred while processing XML file.");
}
});
});
When i try to run this using this URL the browser gives an error saying "An error occurred while processing XML file"........................
But if i download the XML File and write it as following.... It will run the page without any errors.......
$.ajax({
type: "GET",
url: "data.xml",
dataType: "xml",
...................................
I also tried to use another online XML File same thing happened...... Anyone has an idea how to solve this???
Thank You!!!!!

Read local file text (tab separated values) with d3 or ajax cause syntax error in firefox development console

The reading works.
However I got a syntax error in the firefox console (which is tiresome when I read 30 files).
The files are annotation files like (time \t value) with no headers like :
0.0 5.2
0.5 5.6
1.0 6.3
...
This is the ajax code :
function getdatafromfile(filename) {
// Read annotation file. Example : %timeinstant \t %value \n
// Return an array of string
var arraydata
$.ajax({
type: "GET",
url: filename,
dataType: "text",
async: false,
success: function(csv) {arraydata = $.csv.toArrays(csv,{separator:'\t'}); }
});
return arraydata}
And with d3:
d3.text(filename, function(text) {
var data = d3.tsv.parseRows(text).map(function(row) {
return row.map(function(value) {
return +value;
});
});
console.log(data);
});
}
It seems that I could use one of those code, but I got a syntax error in both cases (with firefox 33.1).
A file reader could work like the code below.
In the example I've added a flag to use the content of the variable instead of a file. That's just for the demo and can be removed. The same code is here as jsFiddle.
Maybe you could add some validation before or after the $.csv method. So you know that the file was a csv/tsv file.
If you need to open the file with-out user interaction, you have to look for something different because JS is not allowed to open a file with-out the user choosing the file (security concerns, see this SO question).
You could add your data to a database and read it from there. e.g. Firebase or MongoDB or use a JSON file. The code of my other answer should work for a JSON file that you host with your webpage.
var demoTxt = "0.0 5.2\
0.5 5.6\
1.0 6.3";
var flag_usedemofile = true; //if true var demoTxt will be used
function doOpen(evt) {
var files = evt.target.files,
reader = new FileReader();
reader.onload = function() {
if ( !flag_usedemofile) {
var arraydata = $.csv.toArrays(this.result,{separator:' '});
showout.value = arraydata; //this.result;
} else {
var arraydata = $.csv.toArrays(demoTxt,{separator:' '});
showout.value = arraydata;
console.log(arraydata);
}
};
reader.readAsText(files[0]);
}
var openbtn = document.getElementById("openselect"),
showout = document.getElementById("showresult");
openselect.addEventListener("change", doOpen, false);
#showresult {
width:98%;
height: 300px;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<script src="http://cdnjs.cloudflare.com/ajax/libs/jquery-csv/0.71/jquery.csv-0.71.min.js"></script>
<input type="file" id="openselect" />
<textarea id="showresult"></textarea>
I'm not exactly sure what syntax error you are getting. But I think the error have something to do with the mime type of your json request.
I think the best way is to wrap your data in json and then use JSONP. (I have also tried to get it working with text/plain, but with-out success.)
Please check the following example for details. You can also find the same example on
jsFiddle.
(function ($) {
var url = 'http://www.mocky.io/v2/547c5e31501c337b019a63b0'; // dummy url
var jsonCallback = function (csv) {
var arraydata;
console.log(data);
$('#data').html(JSON.stringify(csv, null, 2));
arraydata = $.csv.toArrays(csv.data,{separator:'\t'});
console.log(arraydata);
};
$.ajax({
type: 'GET',
url: url,
contentType: "application/json",
dataType: 'jsonp'
}).done(jsonCallback)
.fail(function (xhr) {
alert("error" + xhr.responseText);
});
})(jQuery);
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<pre id='data'></pre>

Im not able to decode my file passed from JAVASCRIPt to PHP

I am encoding and passing a file (word document) to php.How can I read this and write to a file?
I have submit button.On submit, I am passing an ajax.Before that, Iam encoding the file with file reader.On submit button, an event 'handleFileSelect' is trtiggered.The file is read as dataurl and sent to php via ajax.
I am able to get the data as encoded.If the file is a text, i am also able to decode .But
its not able to get the contents of a word file.If I decode
How would I do this?
My code :
//File Convertion--Function to convert images to base 64 encoded format
function handleFileSelect(objEvent) {
var strFiles = objEvent.target.files; // FileList object
strInput = document.getElementById('uploaded_file');
strFile = strInput.files[0];
strFiletype=strFile.type;
strFileSize=strFile.size;alert(strFiletype);
strFiletype=strFiletype.split("/");
//Checking wheter the uploaded file is image or not
if(strFiletype[0]!='image') {
for (var i = 0, f; f = strFiles[i]; i++) {
var reader = new FileReader();
// Closure to capture the file information.
reader.onload = (function(theFile) {
return function(e) {
// Render thumbnail.
strGlobalImageData=e.target.result;
};
})(f);
reader.readAsDataURL(f);
}
} else {
alert("NOT A DOC");
}
}
//ajax call to send files to php
var app = 'contact.php';
$.ajax({
url: app,
async: false,
type:"POST",
data : "file="+strGlobalImageData,
dataType: "jsonp",
contentType: 'application/x-www-form-urlencoded',
processData:false,
jsonp: "jsoncallback",
success: function(html) {
alert("Thank you. We will be in touch with you");
},
error: function(){
alert("Thank you. We will be in touch with you");
}
});
//Php side--contact.php
<?php
$files=base64_decode($_POST['file']);
If I decode, I am getting a binary format of the word file
The issue was with character replacing.We need to replace befor decoding the data.The exact code is shown below:
In Php,
$files=trim($_POST['file']);
$strEncodedData= str_replace(' ','+',$files);
$strFilteredData = explode(',',$strEncodedData);
$strDecodedData= base64_decode($strFilteredData[1]);
$arrFiles = explode(",",$files);
file_put_contents("myfile.doc",$strDecodedData);
This content will be written into file "myfile.doc".
Thank you for all effort made by my friends

Saving HTML 5 Canvas as Image on the server using ASP.NET

I need some help here..
Im trying to save a canvas image after drawing..
following this example (http://www.dotnetfunda.com/articles/article1662-saving-html-5-canvas-as-image-on-the-server-using-aspnet.aspx)
$("#btnSave").click(function () {
var image = document.getElementById("canvas").toDataURL("image/png");
image = image.replace('data:image/png;base64,', '');
$.ajax({
type: 'POST',
url: "../../Home/UploadImage?imageData=" + image,
contentType: 'application/json; charset=utf-8',
dataType: 'json',
success: function (msg) {
alert('Image saved successfully !');
}
});
});
the controller:
public void UploadImage(string imageData)
{
string fileNameWitPath = path + DateTime.Now.ToString().Replace("/", "-").Replace(" ", "- ").Replace(":", "") + ".png";
using (FileStream fs = new FileStream(fileNameWitPath, FileMode.Create))
{
using (BinaryWriter bw = new BinaryWriter(fs))
{
byte[] data = Convert.FromBase64String(imageData);
bw.Write(data);
bw.Close();
}
}
}
But when im trying to convert form base64 the string that is passed like parameter in method, throw an error
Invalid length for a character array Base-64.
You can't post data with querystring parameters
Try this;
$("#btnSave").click(function () {
var image = document.getElementById("canvas").toDataURL("image/png");
image = image.replace('data:image/png;base64,', '');
$.ajax({
type: 'POST',
url: "../../Home/UploadImage",
data: '{ "imageData" : "' + image + '" }',
contentType: 'application/json; charset=utf-8',
dataType: 'json',
success: function (msg) {
alert('Image saved successfully !');
}
});
});
In that example, the author has posted the image data using a hidden field, notice below line of code in his article
<input type="hidden" name="imageData" id="imageData" />
http://www.dotnetfunda.com/articles/show/2665/saving-html-5-canvas-as-image-in-aspnet-mvc
And on click of the button, he is submitting the form after getting canvas data to the hidden field so follow the same approach. As written by Mehmet, querystring has limitations and its prone to be modified as it goes via url.
Instead of this
image = image.replace('data:image/png;base64,', '');
use this:
image = image.substr(23, image.length);
remove the leading characters up to the first comma (use any dev tool to see what you posted).

Categories