single and multiple file upload - javascript

I'm facing issue. single and multiple file uploaded file. Then multiple file upload successfully but when single file one by one upload then last one upload other are override by last one. Please help me to find out this problem solution. As you can see below code it's work properly for multiple upload file and send data by ajax then get array value all images but when upload single upload one by one then last one image data get only in ajax data in. please help me to provide me solution.
index.php
`
<!doctype html>
<html lang="en">
<head>
<!-- Required meta tags -->
<meta charset="utf-8">
<meta name="viewport" content="width=device-width, initial-scale=1">
<!-- Bootstrap CSS -->
<link href="https://cdn.jsdelivr.net/npm/bootstrap#5.0.2/dist/css/bootstrap.min.css" rel="stylesheet"
integrity="sha384-EVSTQN3/azprG1Anm3QDgpJLIm9Nao0Yz1ztcQTwFspd3yD65VohhpuuCOmLASjC" crossorigin="anonymous">
<title>Hello, world!</title>
</head>
<style>
#selectedFiles img {
max-width: 200px;
max-height: 200px;
float: left;
margin-bottom: 10px;
}
</style>
<body>
<form id="myForm" method="post">
<input type="file" id="files" class="file_uploader_file" name="files[]" multiple="true" accept="image/*" />
<p class="validateError" id="imgerror" style="color:red;display:none;">Please select your design.</p>
<input type="button" id="fees_stream_submit1" name="submit">
</form>
<script src="http://ajax.googleapis.com/ajax/libs/jquery/1.7.1/jquery.min.js" type="text/javascript"></script>
<script>
(function () {
$(document).on('click', '#fees_stream_submit1', function (e) {
var myfiles = document.getElementById("files");
// var myfiles = $('#files').val();
var files = myfiles.files;
var form = new FormData();
alert(files.length);
for (i = 0; i < files.length; i++) {
form.append('file' + i, files[i]);
}
$.ajax({
url: "fileuploadmultidata.php",
type: "POST",
data: form,
contentType: false,
processData: false,
success: function (result) {
// alert(result);
}
});
});
})();
$(document).ready(function () {
var imgCnt = 0;
var onebyoneImg = [];
var countImg = 1;
if (window.File && window.FileList && window.FileReader) {
$("#files").on("change", function (e) {
var files = e.target.files,
filesLength = files.length;
for (var i = 0; i < filesLength; i++) {
var f = files[i];
// var f = new File([""], files[i]);
var fileReader = new FileReader();
fileReader.onload = (function (e) {
imgCnt++;
alert(imgCnt);
var file = e.target;
$("<span class='pip'><div class=\"file_uploaded_view img-thumb-wrapper image-preview-height\">" +
"<img class=\"img-thumb\" src=\"" + e.target.result + "\" title=\"" + file.name + "\" style='heigh:100px;width:100px'/>" +
"<br/><span class='remove'><i class='fa fa-trash'></i></span></span>" +
"</div>").insertAfter("#files");
$(".remove").click(function () {
$(this).parent(".img-thumb-wrapper").remove();
imgCnt--;
});
});
fileReader.readAsDataURL(f);
}
console.log(f);
});
} else {
alert("Your browser doesn't support to File API")
}
});
</script>
</body>
</html>
`
**fileuploadmultidata.php**
`<?php
echo "<pre>";
print_r($_FILES);die();
?>`

The behaviors of file uploading will be like that only see https://www.w3schools.com/jsref/tryit.asp?filename=tryjsref_fileupload_files
To achieve your requirement you need to store file values in variable and use.
var storeMultiFiles = [];
var file = $(file_id)[0].files;
for(var l=0; l<file.length; l++){
var fileData = file[l];
(function(file) {
var fileReader = new FileReader();
fileReader.readAsDataURL(file);
fileReader.onload = function(oFREvent){
storeMultiFiles.push(oFREvent.target.result)
};
})(fileData);
}
Use files details using "storeMultiFiles" for show, save, update and delete for selected.

Related

how to upload the blob files list to node server using multer

i am currently working on my upload file page and below is the upload function on the client side
and i want the client to check the image first before upload to the server
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta http-equiv="X-UA-Compatible" content="IE=edge">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Upload Testing</title>
</head>
<body>
<h1>Upload img</h1>
<form action="/upload" method="post" enctype="multipart/form-data" id="form"></form>
<button id="submit" onclick="upload()">Submit</button>
<!-- <script src="main.js"></script> -->
<script>
function multipleImageUpload() {
const input = document.createElement("input");
input.setAttribute("type", "file");
input.setAttribute("multiple", "multiple");
const preview = document.createElement("div");
preview.setAttribute("id", "preview");
document.body.appendChild(preview);
input.addEventListener("change", (event) => {
const files = event.target.files;
for (let i = 0; i < files.length; i++) {
const img = document.createElement("img");
img.setAttribute("src", URL.createObjectURL(files[i]));
const removeBtn = document.createElement("button");
removeBtn.innerHTML = "Remove";
removeBtn.addEventListener("click", () => {
preview.removeChild(img);
preview.removeChild(removeBtn);
});
preview.appendChild(img);
preview.appendChild(removeBtn);
}
});
document.getElementById('form').append(input);
}
multipleImageUpload()
function upload(){
const imgs = preview.querySelectorAll("img");
const files = [];
for (let i = 0; i < imgs.length; i++) {
files.push(imgs[i].src);
}
console.log(files);
//submit
// document.getElementById('form').submit()
}
</script>
</body>
</html>
inside the files is blob file link
how to read these array of blob to behave as File
then inlude it inside my form
when i click sumit these blob file must be submitted too in node server
My Server
var express = require('express');
var router = express.Router();
const multer = require('multer')
const upload = multer({
dest:'uploads/'
})
const cpUpload = upload.fields([{name:'files'}])
router.get('/', function(req, res, next) {
res.render('upload/index');
});
router.post('/', cpUpload,(req, res, next)=>{
console.log(req.files);
})
module.exports = router;
i tried converting to files these blob as new File() method but it didnt work because i have to read the blob as file first to add parameter in new File() even if i input it in the File,
i have to put them in the new FormData()
i dont know how that work
when log the form data theres no values

Uploading a cropped image not working CropperJs

I have 2 questions, i am working on a javascript script where i have the following code
<script type="text/javascript" >
function readURL(input) {
if (input.files && input.files[0]) {
var reader = new FileReader();
reader.onload = function (e) {
$('#imageId').attr('src', e.target.result)
};
reader.readAsDataURL(input.files[0]);
setTimeout(initCropper, 1000);
}
}
function initCropper(){
var image = document.getElementById('blah');
var cropper = new Cropper(image, {
aspectRatio: 1 / 1,
crop: function(e) {
console.log(e.detail.x);
console.log(e.detail.y);
}
});
// On crop button clicked
document.getElementById('crop_button').addEventListener('click', function(){
var imgurl = cropper.getCroppedCanvas().toDataURL();
var img = document.createElement("img");
img.src = imgurl;
document.getElementById("cropped_result").appendChild(img);
//sending cropped image to server
cropper.getCroppedCanvas().toBlob(function (blob) {
var formData = new FormData();
formData.append('croppedImage', blob);
// Use `jQuery.ajax` method
path = 'C:/Users/Andy/Desktop/javascript/croppingwcropperjs/uploads';
$.ajax(path, {
method: "POST",
data: formData,
processData: false,
contentType: false,
success: function () {
console.log('Upload success');
},
error: function () {
console.log('Upload error');
}
});
});
})
}
</script>
here is the html part of it
<! DOCTYPE html>
<html>
<head>
<script src="https://cdnjs.cloudflare.com/ajax/libs/cropperjs/1.4.1/cropper.min.js"></script>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<script name="jquery-croper-script">
!function(e,r){"object"==typeof exports&&"undefined"!=typeof module?r(require("jquery"),require("cropperjs")):"function"==typeof define&&define.amd?define(["jquery","cropperjs"],r):r(e.jQuery,e.Cropper)}(this,function(c,s){"use strict";if(c=c&&c.hasOwnProperty("default")?c.default:c,s=s&&s.hasOwnProperty("default")?s.default:s,c.fn){var e=c.fn.cropper,d="cropper";c.fn.cropper=function(p){for(var e=arguments.length,a=Array(1<e?e-1:0),r=1;r<e;r++)a[r-1]=arguments[r];var u=void 0;return this.each(function(e,r){var t=c(r),n="destroy"===p,o=t.data(d);if(!o){if(n)return;var f=c.extend({},t.data(),c.isPlainObject(p)&&p);o=new s(r,f),t.data(d,o)}if("string"==typeof p){var i=o[p];c.isFunction(i)&&((u=i.apply(o,a))===o&&(u=void 0),n&&t.removeData(d))}}),void 0!==u?u:this},c.fn.cropper.Constructor=s,c.fn.cropper.setDefaults=s.setDefaults,c.fn.cropper.noConflict=function(){return c.fn.cropper=e,this}}});
</script>
<link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/cropperjs/1.4.1/cropper.min.css" />
</head>
<body>
<input type="file" name="image" id="image" onchange="readURL(this);"/>
<div class="image_container">
<img id="imageId" src="#" alt="your image" />
</div>
<div id="cropped_result"></div>
<button id="crop_button">Crop</button>
</body>
</html>
Okay. with the code above i intent to crop an image and save the cropped version in my a folder named uploads. I have managed to crop the image however i couldnt save the cropped image. My question are :
what should be the path format in order to successfully commit the cropped image into an upload folder?
i have seen some creating a php script for path like uploads.php is it mandatory for the path to be a script in php.

jszip creating empty txt files of images and zip them

I am using this code to download these Images but This programming making a txt files with these names and with type jpeg . why this is happening ? this programm is not working on chrome due to cross site but on firefox in zip file empty txt files are.
<!DOCTYPE html>
<html>
<body>
<p id="demo"></p>
<script type="text/javascript" src="https://fastcdn.org/FileSaver.js/1.1.20151003/FileSaver.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/jszip/3.1.5/jszip.min.js" type="text/javascript">
</script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/jszip-utils/0.0.2/jszip-utils.min.js" type="text/javascript">
</script>
<script>
var urls = [
"https://s3.amazonaws.com/ais-django/Events/Test1/DSC_0397.jpg",
"https://s3.amazonaws.com/ais-django/Events/Test1/DSC_0398.jpg",
"https://s3.amazonaws.com/ais-django/Events/Test1/DSC_0488.jpg"
];
var nombre = "Zip_img";
//The function is called
compressed_img(urls, nombre);
function compressed_img(urls, nombre) {
var zip = new JSZip();
var count = 0;
var name = nombre + ".zip";
urls.forEach(function(url) {
JSZipUtils.getBinaryContent(url, function(err, data) {
if (err) {
throw err;
}
zip.file(url, data, {
binary: true
});
count++;
if (count == urls.length) {
zip.generateAsync({
type: 'blob'
}).then(function(content) {
saveAs(content, name);
});
}
});
});
}
</script>
</body>
</html>

SheetJS read excel file, my file is not read

So I am trying to use the SheetJS javascript to read in some excel files. I download the SheetJS and I have copied the xlsx.full.min.js in same directory as my html file. However, I do not get it to work. So I tried the code below. The problem is that it does not reach the alert('finished reading'); line. So I do not know if there was a problem reading the source file or what the problem exactly is. I hope somebody can help me with this! Thanks!
<!DOCTYPE html>
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8" />
<style>
</style>
</head>
<body>
<p><input type="file" name="xlfile" id="xlf" /> ... or click here to select a file</p>
<script src="xlsx.full.min.js"></script>
<script>
function handleFile(e) {
//Get the files from Upload control
var files = e.target.files;
var i, f;
//Loop through files
for (i = 0, f = files[i]; i != files.length; ++i) {
var reader = new FileReader();
var name = f.name;
reader.onload = function (e) {
var data = e.target.result;
alert(data);
var result;
alert('reading now');
var workbook = XLSX.read(data, { type: 'binary' });
alert('finished reading');
var sheet_name_list = workbook.SheetNames;
sheet_name_list.forEach(function (y) { /* iterate through sheets */
//Convert the cell value to Json
var roa = XLSX.utils.sheet_to_json(workbook.Sheets[y]);
if (roa.length > 0) {
result = roa;
}
});
//Get the first column first cell value
alert(result[0].Column1);
};
reader.readAsArrayBuffer(f);
}
}
var xlf = document.getElementById('xlf');
if(xlf.addEventListener) xlf.addEventListener('change', handleFile, false);
</script>
</body>
</html>

How to upload a captured and displayed video via phonegap android app

I am using the code below to capture video and display it on the app.
<!DOCTYPE html>
<html>
<head>
<title>Capture Video</title>
<link rel="stylesheet" href="css/jquery.mobile-1.2.0.min.css"/>
<script src="js/jquery-1.8.2.min.js"></script>
<script src="js/jquery.mobile-1.2.0.min.js"></script>
<script type="text/javascript" charset="utf-8" src="cordova.js"></script>
<script type="text/javascript" charset="utf-8" src="js/json2.js"></script>
<script type="text/javascript" charset="utf-8">
// Called if something bad happens.
//
function captureError(error) {
var msg = 'An error occurred during capture: ' + error.code;
navigator.notification.alert(msg, null, 'Uh oh!');
}
// A button will call this function
//
function captureVideo() {
// Launch device video recording application,
// allowing user to capture only 1 video clips with 10mins duration
navigator.device.capture.captureVideo(captureSuccess, captureError, {limit: 1, duration: 10});
}
// Called when capture operation is finished
// to display the captured video
function captureSuccess(s) {
console.log("Success");
console.dir(s[0]);
var v = "<video controls='controls'>";
v += "<source src='" + s[0].fullPath + "' type='video/mp4'>";
v += "</video>";
document.querySelector("#videoArea").innerHTML = v;
}
// This function is to upload the captured video when the user
// clicks upload video button
function uploadFile(mediaFile) {
var ft = new FileTransfer(),
path = mediaFile.fullPath,
name = mediaFile.name;
var options = new FileUploadOptions();
options.mimeType = "documents";
options.fileName = name;
options.chunkedMode = true;
ft.upload(path,
"http://www.example.com/upload.php",
function(result) {
alert('Upload success: ' + result.responseCode);
alert(result.bytesSent + ' bytes sent');
},
function(error) {
alert('Error uploading file ' + path + ': ' + error.code);
},
options);
}
</script>
</head>
<body>
<button onclick="captureVideo();">Capture Video</button> <br><br>
<div id="videoArea"></div><br><br>
<button id="uploadvid" onclick="uploadFile();">Upload Video</button>
</body>
</html>
After displaying the captured video, when the "Upload Video" button is clicked nothing happens. The video is not uploaded to the server. Meanwhile, if I replaced the captureSuccess(s) function with the following code;
function captureSuccess(mediaFiles) {
var i, len;
for (i = 0, len = mediaFiles.length; i < len; i += 1) {
uploadFile(mediaFiles[i]);
}
}
the captured video is uploaded to the server successfully though without preview.
Please could somebody tell me what I'm doing wrong. I want the user to have a look at the captured video first before clicking the "Upload Video" button. Thanks.
The problem with your code is that the onclick="uploadFile();"is not accepting any argument but your function uploadFile(mediaFile) is expecting an argument.
<button id="uploadvid" onclick="uploadFile();">Upload Video</button>
My suggestion for solution is ,create the button element as
<button id="uploadvid" >Upload Video</button>
Write your function captureSuccess as
function captureSuccess(s) {
console.log("Success");
console.dir(s[0]);
var v = "<video controls='controls'>";
v += "<source src='" + s[0].fullPath + "' type='video/mp4'>";
v += "</video>";
document.querySelector("#videoArea").innerHTML = v;
//here you write logic when upload button is clicked
$("#uploadvid").on("click",function(){
uploadFile(s[0]);
});
}

Categories