i am checking mime type validation using magic number hex value of a file type but its not working its not able to check and returning wrong alert message even if the file have right hex value as header.
Below is the details in code:
jQuery(document).ready(function() {
jQuery.fn.hasMimetype = function(ctrl) {
try {
ctrl.value = null;
} catch(ex) { }
if (ctrl.value) {
ctrl.parentNode.replaceChild(ctrl.cloneNode(true), ctrl);
}
}
const fileSelector2 = document.getElementById('file')
jQuery('#file').change(function(event) {
const file = event.target.files[0]
//alert(file.type);
const filereader = new FileReader()
filereader.onloadend = function(evt) {
var header2 = "";
var arr = (new Uint8Array(evt.target.result)).subarray(0, 4);
for(var i = 0; i < arr.length; i++) {
header2 += arr[i].toString(16);
}
if(header2 !=='d0cf11e0' || header2 !=='504b34'){
alert(header2);
alert("only doc/docx files are supported");
$('#file').hasMimetype(fileSelector2);
}
}
filereader.readAsArrayBuffer(file);
});
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<input type="file" id="file" name="file" />
This will always be true, regardless of the value of header2:
if(header2 !=='d0cf11e0' || header2 !=='504b34')
You probably want this instead:
if(header2 !=='d0cf11e0' && header2 !=='504b34')
Related
I have these codes to display the names of the files selected from input and it will preview the FIRST image:
function readURL(input) {
if (input.files && input.files[0]) {
var reader = new FileReader();
reader.onload = function (e) {
var filename = input.value;
var lastIndex = filename.lastIndexOf("\\");
if (lastIndex >= 0) {
filename = filename.substring(lastIndex + 1);
}
var files = $('#my_file')[0].files;
for (var i = 0; i < files.length; i++) {
$("#files").append('<div class="filename"><span name="fileNameList">'+files[i].name+'</span></div>');
}
$("#nextBtn").on("click",function(){
})
$('#myImg').attr('src', e.target.result);
}
reader.readAsDataURL(input.files[0]);
}
}
What i want to do is that when i click on the "next" button,it will go to the next image selected or if i click on the "prev" button,it will go to the previous image(the last image if im displaying the first one).How do i go about doing this?Thank You.
UPDATE:
var fileInput = document.getElementById("my_file");
$(fileInput).on("change",function(event){
var next = document.getElementById("nextBtn");
next.onclick = function(xFlip){
curImage = curImage+xFlip;
var files = event.target.files;
if(curImage > files.length){
curImage = 1;
}
if(curImage == 0){
curImage = files.length;
}
$("#myImg").attr('src',files[curImage-1]);
};
console.log(document.getElementById("myImg").getAttribute("src"));
});
I did it this way as the images are retrieved from input type file multiple.
https://jsfiddle.net/bfr6wp7e/2/
Thanks for the challenge, it was my first meeting with the File API :)
Here is the jsFiddle with what I believe is the correct answer to your question:
https://jsfiddle.net/mkbctrll/aq9Laaew/300936/
JS part
const fileInupt = document.getElementById('fileInput')
const fileList = document.getElementById('fileList')
const slickSettings = {
infinite: true,
speed: 300,
slidesToShow: 1,
slidesToScroll: 1,
autoplay: true
}
const initSlickCarousel = (target, settings) => {
$(target).slick(settings);
}
const handleInputChange = (event) => {
console.log('We are handling it sir!')
const filesArray = Array.from(event.target.files)
filesArray.map((singleFile) => {
const outputImg = document.createElement('img')
const fileReader = new FileReader()
outputImg.className = 'img-thumbnail'
// Let's read it as data url - onload won't return a thing without it
fileReader.readAsDataURL(singleFile)
fileReader.onload = (event) => { outputImg.src = event.target.result }
console.log(outputImg)
fileList.appendChild(outputImg)
})
initSlickCarousel(fileList, slickSettings)
}
if(window.File && window.FileReader && window.FileList) { // check if browser can handle this
console.log('We are good to go sir!')
fileInput.addEventListener('change', handleInputChange, false)
} else {
alert('File features are not fully supported. Please consider changing the browser (newest Chrome or Mozilla).')
}
Though it won't be possible for me to get a grasp on that tech if not for the following sources:
https://www.html5rocks.com/en/tutorials/file/dndfiles/
https://developer.mozilla.org/en-US/docs/Web/API/FileReader
https://developer.mozilla.org/en-US/docs/Web/API/FileReader/onload
Sample code for Prev and Next image slide.
var numImages = 4;
var curImage = 1;
var imgArray =[
"one.jpg",
"two.jpg",
"three.jpg",
"four.jpg"
];
function imageShow( xflip ) {
curImage = curImage + xflip;
if (curImage > numImages)
{ curImage = 1 ; }
if (curImage == 0)
{ curImage = numImages ; }
document.images[2].src = imgArray[curImage - 1];
}
HTML buttons:
<input type="button" value="<< Prev" onclick="imageShow(-1)">
<input type="button" value="Next >>" onclick="imageShow(1)">
I have an aspx page which already has a code for uploading file using "asp:FileUpload" and webform. On a different section of page, I want to add the functionality for a user to upload file. But i do not want to use webforms or "asp:fileupload".
So, I created an HTML file that i inject as an iframe inside a div tag on the aspx.
<div id="iUploadDoc" style="height:50px;">
<iframe name='FileUpload' id='FileUpload' class='iUploadFrame' width='100%' frameborder='0' border='0'src='DocUpload.htm'></iframe></div>
I set the EnablePageMethods to true.
<asp:ScriptManager ID="ScriptManager1" runat="server" EnablePageMethods="true">
And inside the HTML I made a form and with input type file.
<form method="POST" action="DocDetail.aspx.cs" id="docUpload" enctype="multipart/form-data">
<div>
<label for="fileUpload" class="inputLabel">Upload File</label>
<input type="file" id="fileUpload" name="files"/>
</div>
</form>
<div id="progUpload" style="display: none;">
<p class="uploadBox">Uploading...</p>
</div>
<span id= "selectedFile" style="display: none;"></span><span id="fileName" style="display: none;"></span>
Now, I dont know what to put in the "action" param of form.
First on the iframe, below is the script i wrote:
window.onload = load;
function uploadDocFile() {
var prog = document.getElementById("progUpload");
prog.style.cssText = 'display: block;';
var x = document.getElementById("fileUpload");
var txt = "";
var filePath = "";
var fileName = "";
if (x.value == "") {
txt += "Select a file.";
document.getElementById("selectedFile").innerHTML = txt;
} else {
filePath = x.value;
fileName = filePath.replace(/^.*[\\\/]/, '');
txt += "<br>Selected file: ";
document.getElementById("selectedFile").innerHTML = txt;
document.getElementById("fileName").innerHTML = fileName;
}
var formInfo = document.getElementById("docUpload");
document.getElementById("docUpload").style.display = "none";
window.parent.getFormData(formInfo, x ,x.value, fileName);
}
function load() {
var e = document.getElementById("fileUpload");
//var formInfo = document.getElementById("docUpload");
//fakeClick();
e.onchange = function () {
uploadDocFile();
}
}
Then on the parent page, below is the script i wrote.
DocUpload.prototype.uploadFileDoc= function (formInfo, uploadedFile, fileInfo, lastModifiedDate, name, extension, size, type) {
//blacklitsType is an array of types of file (similarly for blacklistExt) that should not be allowed to upload
if (indexOf.call(blackListType, type) < 0 && indexOf.call(blackListExt, extension) < 0) {
var idParams = { OiD: ordId, pID: pId, QID: qId }
var files = uploadedFile.files;
var fileEntries = [];
for (j = 0, len1 = files.length; j < len1; j++) {
file = files[j];
if (file.getAsEntry) {
entry = file.getAsEntry();
} else if (file.webkitGetAsEntry) {
entry = file.webkitGetAsEntry();
}
if (entry) {
isFyl = entry.isFile;
if (!isFyl) {
alert("You can not upload a folder. Uploading files (if present).");
} else {
fileItem = file.getAsFile();
fileEntries.push(fileItem);
}
} else if (!file.type && file.size % 4096 === 0) {
alert("You can not upload a folder. Uploading files (if present).");
} else {
fileEntries.push(file);
}
}
PageMethods.UploadDocument(fileEntries[0], idParams, function (res) {
if (res == true) {
alert("File uploaded successfully.");
} else {
alert("File upload failed.");
}
}, function (err) {
alert("ERROR: " + err._message);
});
} else {
window.alert('You cannot upload incorrect file types.');
}
return;
};
DocUpload.prototype.getFormData = function (formInfo, uploadedFile, fileInfo, nameInfo) {
var currDate, extension, lastModifiedDate, name, nameArr, size, type;
currDate = new Date();
lastModifiedDate = currDate;
type = '';
size = 512;
name = nameInfo;
nameArr = name.split(".");
extension = nameArr[nameArr.length - 1];
DocUpload.prototype.uploadFileDoc(formInfo, uploadedFile, fileInfo, lastModifiedDate, name, extension, size, type);
};
window.getFormData = DocUpload.prototype.getFormData;
The transfer of attributes of form from iframe to parent page work just fine. But how should i post it as file using PageMethod. Below is the page method in my code behind:
[System.Web.Services.WebMethod()]
[System.Web.Script.Services.ScriptMethod(UseHttpGet = false)]
public static bool UploadDocument(HttpPostedFileBase uploadedFile,IdParams idParams) {
bool err = false;
try{
//code
err= true;}
catch(Exception ex){err = false;}
return err;
}
No matter how much tried, either I keep getting error regarding HTTPPostedFileBase or Serialization of child not allowed.Below are only some of the errors i keep getting (not at the same time):
No parameterless constructor System.Web.HttpPostedFileBase aspx, OR
The formatter threw an exception while trying to deserialize the message: There was an error while trying to deserialize parameter
What should i do?
Found this article which showing how to distinguish file upload from directory How to handle dropped folders but they not explain how I can handle the directory upload. Having difficulties to find any example. Anyone know how to get File instance of each file in directory?
Copied from that article:
<div id=”dropzone”></div>
var dropzone = document.getElementById('dropzone');
dropzone.ondrop = function(e) {
var length = e.dataTransfer.items.length;
for (var i = 0; i < length; i++) {
var entry = e.dataTransfer.items[i].webkitGetAsEntry();
if (entry.isFile) {
... // do whatever you want
} else if (entry.isDirectory) {
... // do whatever you want
}
}
};
Use DirectoryReader directoryEntry.createReader() , readEntries() for folders or , FileEntry file() for single or multiple file drops.
html
<div id="dropzone"
ondragenter="event.stopPropagation(); event.preventDefault();"
ondragover="event.stopPropagation(); event.preventDefault();"
ondrop="event.stopPropagation(); event.preventDefault(); handleDrop(event);">
Drop files
</div>
javascript
function handleFiles(file) {
console.log(file);
// do stuff with `File` having `type` including `image`
if (/image/.test(file.type)) {
var img = new Image;
img.onload = function() {
var figure = document.createElement("figure");
var figcaption = document.createElement("figcaption");
figcaption.innerHTML = file.name;
figure.appendChild(figcaption);
figure.appendChild(this);
document.body.appendChild(figure);
URL.revokeObjectURL(url);
}
var url = URL.createObjectURL(file);
img.src = url;
} else {
console.log(file.type)
}
}
function handleDrop(event) {
var dt = event.dataTransfer;
var files = dt.files;
var length = event.dataTransfer.items.length;
for (var i = 0; i < length; i++) {
var entry = dt.items[i].webkitGetAsEntry();
if (entry.isFile) {
// do whatever you want
console.log("isFile", entry.isFile);
entry.file(handleFiles);
} else if (entry.isDirectory) {
// do whatever you want
console.log("isDirectory", entry.isDirectory);
var reader = entry.createReader();
reader.readEntries(function(entries) {
entries.forEach(function(dir, key) {
dir.file(handleFiles);
})
})
}
}
}
plnkr http://plnkr.co/edit/eGAnbA?p=preview
After you drag some file from your disk. This event.dataTransfer.file is your fileList object.
Your could create a formData then
Add files from fileList to formData one by one.
In the end you could submit formData to server with Ajax
This is the first time I am working with JavaScript modules. I am trying to upload an image and show it in a div under 'id="imageholder"'.
The error is:
uncaught type error :can't find property 'fileread' of undefined
HTML:
<html>
<body>
<div id='imageholder' style='width:100px;height:100px;border:1px solid black;position:relative;left:100px;'></div>
<input type='file' id='up' />
<script src='myscript.js'></script>
<script>
document.getElementById('up').addEventListener('change', FileUpload.files, false);
</script>
</body>
</html>
Here is the myscript.js module file which should return the object called FileUpload. But error is saying it is undefined. Why it is
undefined? It is long but it works when I don't use it like a module but all in a single file.
You can jump at the end and can see I am returning an object literal to FileUpload variable.
var FileUpload = (function(fileElement) {
var imageholder = document.getElementById('imageholder');
function getBLOBFileHeader(url, blob, callback, callbackTwo) {
var fileReader = new FileReader();
fileReader.onloadend = function(e) {
var arr = (new Uint8Array(e.target.result)).subarray(0, 4);
var header = "";
for (var i = 0; i < arr.length; i++) {
header += arr[i].toString(16);
}
console.log(header);
var imgtype = callback(url, header); // headerCallback
callbackTwo(imgtype, blob)
};
fileReader.readAsArrayBuffer(blob);
}
function headerCallback(url, headerString) {
var info = getHeaderInfo(url, headerString);
return info;
}
function getTheJobDone(mimetype, blob) {
var mimearray = ['image/png', 'image/jpeg', 'image/gif'];
if (mimearray.indexOf(mimetype) != -1) {
printImage(blob);
} else {
fileElement.value = '';
while (imageholder.firstChild) {
imageholder.removeChild(imageholder.firstChild);
}
// alert('you can not upload this file type');
}
}
function remoteCallback(url, blob) {
getBLOBFileHeader(url, blob, headerCallback, getTheJobDone);
}
function printImage(blob) {
// Add this image to the document body for proof of GET success
var fr = new FileReader();
fr.onloadend = function(e) {
var img = document.createElement('img');
img.setAttribute('src', e.target.result);
img.setAttribute('style', 'width:100%;height:100%;');
imageholder.appendChild(img);
};
fr.readAsDataURL(blob);
}
function mimeType(headerString) {
switch (headerString) {
case "89504e47":
type = "image/png";
break;
case "47494638":
type = "image/gif";
break;
case "ffd8ffe0":
case "ffd8ffe1":
case "ffd8ffe2":
type = "image/jpeg";
break;
default:
type = "image/pjpeg";
break;
}
return type;
}
function getHeaderInfo(url, headerString) {
return (mimeType(headerString));
}
// Check for FileReader support
function fileread(event) {
if (window.FileReader && window.Blob) {
/* Handle local files */
var mimetype;
var mimearray = ['image/png', 'image/jpeg', 'image/gif'];
var file = event.target.files[0];
if (mimearray.indexOf(file.type) === -1 || file.size >= 2 * 1024 * 1024) {
while (imageholder.firstChild) {
imageholder.removeChild(imageholder.firstChild);
}
fileElement.value = '';
file = null;
return false;
} else {
while (imageholder.firstChild) {
imageholder.removeChild(imageholder.firstChild);
}
remoteCallback(file.name, file);
}
} else {
// File and Blob are not supported
console.log('file and blob is not supported');
}
}
return {
files: fileread
};
}(document.getElementById('up')))
it's working right as you provided it jsfiddle.net/fredo5n8/ here is the proof.
Are you sure you did not forget to wipe cache in your browser? If that's the case, try to run the code in incognito (private) window.
EDIT:
<html>
<body>
<div id='imageholder' style='width:100px;height:100px;border:1px solid black;position:relative;left:100px;'></div>
<input type='file' id='up' />
<script id='myscript' src='myscript.js'></script>
<script>
var script = document.getElementById('myscript');
var attachInputEvents = function () {
document.getElementById('up').addEventListener('change', FileUpload.files, false);
}
script.onload=attachInputEvents();
</script>
</body>
</html>
This way, you'll wait for the srcript to load(I guess that's the problem, cause locally on my machine even with separate files, it worked good hosted on WAMP server)
I want to count words from below file types..
['pdf','xls','xlsx','odt','ppt','pptx','txt','doc','docx','rtf']/
currently my code reads text files only..
please help me for other file types..
Below is my code..
<script>
$('#file').change( function(event) {
var imgpath=document.getElementById('file');
if (!imgpath.value==""){
var ext = imgpath.value.split('.').pop().toLowerCase();
if($.inArray(ext, ['pdf','xls','xlsx','odt','ppt','pptx','txt','doc','docx','rtf']) != -1) {
var f = event.target.files[0];
if (f) {
var r = new FileReader();
r.onload = function(e) {
var strings = "";
var contents = e.target.result; alert(contents);
var words = contents.match(/\S+/g).length;
$('#display_file_count').text(words);
}
r.readAsText(f);
}
}else{
alert('file type not supported.');
$('#file').val('');
}
}
});
</script>