Error uploading file to Parse - javascript

I am trying to load file (pdf) into parse, but nothing is showing up in my parse so I am assuming an error lies in the following code (note I created a new custom class scan).
<HTML>
<head>
<script type="text/javascript" src="https://ajax.googleapis.com/ajax/libs/jquery/1.7.2/jquery.min.js"></script>
</head>
<body>
<form id="fileupload" name="fileupload" enctype="multipart/form-data" method="post">
<input type="file" id="pic">
<input type="submit" value="Submit">
</form>
<script type="text/javascript">
Parse.initialize("id", "id");
var products = Parse.Object.extend("Product");
var fileUploadControl = $("#pic")[0];
if (fileUploadControl.files.length > 0) {
var file = fileUploadControl.files[0];
var name = "photo.png";
var parseFile = new Parse.File(name, file);
}
parseFile.save().then(function() {
//The file has been saved to Parse.
}, function(error) {
// The file either could not be read, or could not be saved to Parse.
});
</script>
</head>
</body>
</HTML>
Any help would be greatly appreciated.

Related

How do I rename a file after uploading it?

I have this input type, if I upload a file with less than 8 length add zeros, but what I need is to change my input with the new name.
<body>
<input type="file" id="upload" />
<script>
$(document).ready(function(){
$('#upload').change(function(e){
var fileName = e.target.files[0].name;
var newName = fileName.substring(0,fileName.length-4);
while(newName.length<8){
newName = "0"+newName;
}
console.log(e.target.files[0].name=newName);
});
});
</script>

Get the extension of a file but can't get the filename

I am trying to check if a file has a valid extension or not. The problem is that when I give the file a random extension like .txt it doesn't get caught.
I think the problem is that I am not actually getting the full filename.
<script type="text/javascript">
function getExtension(fileName)
{
var parts = fileName.split('.');
return parts[parts.length - 1];
}
function isVideo(fileName)
{
var ext = getExtension(fileName);
switch (ext.toLowerCase())
{
case 'mp4': return true;
}
return false;
}
function check()
{
var f = document.getElementsByID('file');
if(isVideo(f.value) && document.getElementById('file').value)
{
return true;
}
document.getElementById('errMsg').style.display = '';
return false;
}
</script>
The PHP form:
<?php
$nexturl = "http://localhost/index.php";
?>
<form action="<?php echo($response->url); ?>?nexturl=<?php echo(urlencode($nexturl)); ?>" method="post" enctype="multipart/form-data" onsubmit="return check();">
<input id="file" type="file" name="file"/>
<div id="errMsg" style="display:none;color:red">
Bad file type.
</div>
<input type="hidden" name="token" value="<?php echo($response->token); ?>"/>
<input type="submit" value="go" />
</form>
</php>
You could first obtain the file extension and then do what you need to with it:
var patt1 = /\.[0-9a-z]+$/i;
var fileName = "file.zip";
var theReturn = fileName.match(patt1);
alert(theReturn); //returns .zip
So, in your code, you would need to switch your switch statement to the following:
function isVideo(fileName)
{
var patt1 = /\.[0-9a-z]+$/i;
var fileName = "file.zip";
var theReturn = fileName.match(patt1);
switch (theReturn.toLowerCase())
{
case '.mp4': return true; //make sure it's .mp4 instead of just mp4
}
retrun false
}
EDIT
Example to get file name and extension of uploaded file to FileUpload control:
HTML
<!DOCTYPE Html />
<html>
<head>
<title></title>
</head>
<body>
<input id="File1" type="file" />
<input type="button" id="btnGetExt" value="Get File Extension"/>
<script type="text/javascript" src="theJS.js"></script>
</body>
</html>
JavaScript
btnGetExt.onclick = function () {
var patt1 = /\.[0-9a-z]+$/i;
var fileName = document.getElementById('File1').value;
alert(fileName);
var theReturn = fileName.match(patt1);
alert(theReturn);
}

Acces a file in a file upload input [duplicate]

I actually have a file input and I would like to retrieve the Base64 data of the file.
I tried:
$('input#myInput')[0].files[0]
to retrieve the data. But it only provides the name, the length, the content type but not the data itself.
I actually need these data to send them to Amazon S3
I already test the API and when I send the data through html form with encode type "multipart/form-data" it works.
I use this plugin : http://jasny.github.com/bootstrap/javascript.html#fileupload
And this plugins gives me a preview of the picture and I retrieve data in the src attribute of the image preview. But when I send these data to S3 it does not work. I maybe need to encode the data like "multipart/form-data" but I don't know why.
Is there a way to retrieve these data without using an html form?
input file element:
<input type="file" id="fileinput" />
get file :
var myFile = $('#fileinput').prop('files');
You can try the FileReader API. Do something like this:
<!DOCTYPE html>
<html>
<head>
<script>
function handleFileSelect()
{
if (!window.File || !window.FileReader || !window.FileList || !window.Blob) {
alert('The File APIs are not fully supported in this browser.');
return;
}
var input = document.getElementById('fileinput');
if (!input) {
alert("Um, couldn't find the fileinput element.");
}
else if (!input.files) {
alert("This browser doesn't seem to support the `files` property of file inputs.");
}
else if (!input.files[0]) {
alert("Please select a file before clicking 'Load'");
}
else {
var file = input.files[0];
var fr = new FileReader();
fr.onload = receivedText;
//fr.readAsText(file);
//fr.readAsBinaryString(file); //as bit work with base64 for example upload to server
fr.readAsDataURL(file);
}
}
function receivedText() {
document.getElementById('editor').appendChild(document.createTextNode(fr.result));
}
</script>
</head>
<body>
<input type="file" id="fileinput"/>
<input type='button' id='btnLoad' value='Load' onclick='handleFileSelect();' />
<div id="editor"></div>
</body>
</html>
I created a form data object and appended the file:
var form = new FormData();
form.append("video", $("#fileInput")[0].files[0]);
and i got:
------WebKitFormBoundaryNczYRonipfsmaBOK
Content-Disposition: form-data; name="video"; filename="Wildlife.wmv"
Content-Type: video/x-ms-wmv
in the headers sent. I can confirm this works because my file was sent and stored in a folder on my server. If you don't know how to use the FormData object there is some documentation online, but not much. Form Data Object Explination by Mozilla
Html:
<input type="file" name="input-file" id="input-file">
jQuery:
var fileToUpload = $('#input-file').prop('files')[0];
We want to get first element only, because prop('files') returns array.
input element, of type file
<input id="fileInput" type="file" />
On your input change use the FileReader object and read your input file property:
$('#fileInput').on('change', function () {
var fileReader = new FileReader();
fileReader.onload = function () {
var data = fileReader.result; // data <-- in this var you have the file data in Base64 format
};
fileReader.readAsDataURL($('#fileInput').prop('files')[0]);
});
FileReader will load your file and in fileReader.result you have the file data in Base64 format (also the file content-type (MIME), text/plain, image/jpg, etc)
FileReader API with jQuery, simple example.
( function ( $ ) {
// Add click event handler to button
$( '#load-file' ).click( function () {
if ( ! window.FileReader ) {
return alert( 'FileReader API is not supported by your browser.' );
}
var $i = $( '#file' ), // Put file input ID here
input = $i[0]; // Getting the element from jQuery
if ( input.files && input.files[0] ) {
file = input.files[0]; // The file
fr = new FileReader(); // FileReader instance
fr.onload = function () {
// Do stuff on onload, use fr.result for contents of file
$( '#file-content' ).append( $( '<div/>' ).html( fr.result ) )
};
//fr.readAsText( file );
fr.readAsDataURL( file );
} else {
// Handle errors here
alert( "File not selected or browser incompatible." )
}
} );
} )( jQuery );
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<input type="file" id="file" />
<input type='button' id='load-file' value='Load'>
<div id="file-content"></div>
To read as text... uncomment //fr.readAsText(file); line and comment fr.readAsDataURL(file);
Get file using jquery
element html:
<input id="fileInput" type="file" />
jquery code:
$("#fileInput")[0].files[0]
this work for me :)
HTML
<div class="row form-group my-2">
<div class="col-12">
<div class="">
<div class="text-center">
<label for="inpImage" class="m-2 pointer">
<img src="src/img/no-image.jpg" id="img-visor" height="120" class="rounded mx-auto d-block">
</label>
<input type="file" class="visually-hidden" accept="image/*" name="picture" id="inpImage">
</div>
</div>
</div>
</div>
jQuery
$('#inpImage').change(()=>{
const file = $('#inpImage').prop("files")[0];
const imagen = URL.createObjectURL(file);
console.log(URL.createObjectURL(file));
$('#img-visor').attr('src', imagen);
});
<script src="~/fileupload/fileinput.min.js"></script>
<link href="~/fileupload/fileinput.min.css" rel="stylesheet" />
Download above files named fileinput add the path i your index page.
<div class="col-sm-9 col-lg-5" style="margin: 0 0 0 8px;">
<input id="uploadFile1" name="file" type="file" class="file-loading"
`enter code here`accept=".pdf" multiple>
</div>
<script>
$("#uploadFile1").fileinput({
autoReplace: true,
maxFileCount: 5
});
</script>
<!DOCTYPE html>
<html>
<head>
<script>
function handleFileSelect()
{
if (!window.File || !window.FileReader || !window.FileList || !window.Blob) {
alert('The File APIs are not fully supported in this browser.');
return;
}
var input = document.getElementById('fileinput');
if (!input) {
alert("Um, couldn't find the fileinput element.");
}
else if (!input.files) {
alert("This browser doesn't seem to support the `files` property of file inputs.");
}
else if (!input.files[0]) {
alert("Please select a file before clicking 'Load'");
}
else {
var file = input.files[0];
var fr = new FileReader();
fr.onload = receivedText;
//fr.readAsText(file);
//fr.readAsBinaryString(file); //as bit work with base64 for example upload to server
fr.readAsDataURL(file);
}
}
function receivedText() {
document.getElementById('editor').appendChild(document.createTextNode(fr.result));
}
</script>
</head>
<body>
<input type="file" id="fileinput"/>
<input type='button' id='btnLoad' value='Load' onclick='handleFileSelect();' />
<div id="editor"></div>
</body>
</html>

On clicking the submit button it is not giving appropriate result

Hello ,
I am having some problem with javascript & Html..In my code i am reading excel file from directory and showing some output..for this i have a file input type and a Button...what is happening here is when i select the xls file and click on submit button Choose a file widow is opening every time when i am clicking on the submit button ..
the code is as follows
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="utf-8" />
<title>Speedometer HTML5 Canvas</title>
<script src="script copy.js"></script>
</head>
<body onload='draw(0);'>
<canvas id="tutorial" width="440" height="220">
Canvas not available.
</canvas>
<div>
<form id="drawTemp">
<input type="text" id="txtSpeed" name="txtSpeed" value="20" maxlength="2" />
<input type="button" value="Draw" onclick="drawWithInputValue();">
<input type=file id="fileInput" value="">
<input type=button value="submit" onclick="readdata(1,1);">
</form>
</div>
</body>
</html>
<script type="text/javascript" language="javascript">
function checkfile(sender) {
var validExts = new Array(".xlsx", ".xls", ".csv");
var fileExt = sender.value;
fileExt = fileExt.substring(fileExt.lastIndexOf('.'));
if (validExts.indexOf(fileExt) < 0) {
alert("Invalid file selected, valid files are of " +
validExts.toString() + " types.");
return false;
}
else return true;
}
var xVal = 1;
var yVal = 2
function readdata(x,y) {
x = xVal;
y = yVal;
// Use the <input type='file'...> object to get a filename without showing the object.
document.all["fileInput"].click();
var fileName = document.all["fileInput"].value;
try {
var excel = new ActiveXObject("Excel.Application");
excel.Visible = false;
var excel_file = excel.Workbooks.Open(fileName);
var excel_sheet = excel_file.Worksheets("Sheet1");
var data = excel_sheet.Cells(x, y).Value;
//alert(data);
drawWithexcelValue(data);
xVal = xVal + 1;
}
catch (ex) {
alert(ex);
}
}
</script>
Every time i click on the submit button it opens the choose window to choose file ..why my button is behaving like file type input..
It's opening the "choose file" dialog because of this line in your Javascript:
document.all["fileInput"].click();
If you remove that, you won't get this behaviour.
document.all["fileInput"].click();
when you click on submit this line in the readdata() function is programmatically clicking on the choose file button.

how to get file size in javascript or jquery with rails

how to get file size in javascript or jquery with rails here by word size i means to say content size of file like 100kb.
here i got some methods like size or file size but its not working for me
my ruby code is
<%= upload_form.file_field :upload_file_name1,:onchange =>"return validateFileExtension(this)"%>
function validateFileExtension(fld) {
alert(fld.value.fileSize);
if(!/(\.jpg|\.gif|\.png)$/i.test(fld.value)) {
alert("Invalid file type! Kindly upload in a JPG, GIF or PNG format!");
fld.parentNode.innerHTML = fld.parentNode.innerHTML;
fld.focus();
return false;
}
return true;
}
<html>
<head>
<script language="JavaScript">
function A()
{
var oas = new ActiveXObject("Scripting.FileSystemObject");
var d = document.a.b.value;
var e = oas.getFile(d);
var f = e.size;
alert(f + " bytes");
}
</script>
</head>
<body>
<form name="a">
<input type="file" name="b">
<input type="button" name="c" value="SIZE" onClick="A();">
</form>
</body>
</html>

Categories

Resources