How to upload image via Javascript? - javascript

I am trying to upload an image to an input[type='file'] of another page.
Here is what I have so far:
const dT = new ClipboardEvent('').clipboardData || new DataTransfer();
dT.items.add(new File(result.products[pointer][3], 'product_image.png'));
document.querySelector('input[class="mkhogb32"]').files = dT.files;
console.log(dT);
console.log(document.querySelector('input[class="mkhogb32"]').files);
The code goes through and creates a file and adds it to the inputs files, however, the image never actually gets uploaded to the page:
Terminal of page
The image above shows the files of the input after my function ran, showing the function went through. However, on this particular page, when an image is uploaded the traditional way off picking a file off your desktop or drag and drop it changes the css, as it displays the image.
How can I get my injected file to trigger that same reaction?
The result.products[pointer][3] refers to an image src scraped from a previous page, how can I make the injected file contain this image?

In this example I'm picking a local image. The FileReader object will read the file as a data URL and when ready ('load') it will insert the data URL into the src attribute if the image.
var reader1 = new FileReader();
reader1.addEventListener('load', e => {
document.querySelector('#img').src = e.target.result;
});
document.addEventListener('DOMContentLoaded', e => {
document.forms.pickfile.file.addEventListener('change', e => {
reader1.readAsDataURL(e.target.files[0]);
});
});
<form name="pickfile">
<input name="file" type="file" />
</form>
<img id="img" />

I don't think that it is possible to add a file to an input[type="file"] element using JavaScript, but you can grab the formdata from a form and then add your own data to formdata.
In the example: When the user click on the submit I "copy" the formdata from the form (OK, there is no data in this example, but still...). I create a file object (maybe you already have a file object or a list of file objects) and set that as an object in formData. Lastly I post the formData as if it was a plain POST submit from the form.
Maybe this can help...
document.forms.pickfile.addEventListener('submit', e => {
e.preventDefault();
let svg = ['<?xml version="1.0"?><svg xmlns="http://www.w3.org/2000/svg" width="200" height="200"><rect fill="blue" width="200" height="200" x="0" y="0"/></svg>'];
let file = new File(svg, 'example.svg', {type: 'image/svg'});
let formData = new FormData(e.target);
formData.set('file', file, 'example.svg');
fetch('/', {
method: 'POST',
body: formData
})
.then(response => response.json())
.then(data => console.log(data));
});
<form name="pickfile">
<input name="file" type="file" />
<button>Send</button>
</form>

Related

$_FILES is empty when I load images with javascript

I have a form to edit existing data but for some reason the images I load are not being detected in the var $_FILES.
The var $_FILES only detect data If I upload more images manually (without javascript code).
Here is my code to load images to the form.
// This images are loaded after the query is executed and then
// I take this images and insert in the form.
var images = document.getElementsByClassName("image-product");
var dataTransfer = new DataTransfer();
for (let image of images) {
fetch(image.src).then(res => res.blob()).then(blob => {
var file = new File([blob], image.id, blob);
dataTransfer.items.add(file);
listImagesForm.push(file);
});
}
var iptImg = document.getElementById("ipt-image");
iptImg.files = dataTransfer.files;
But if I go to the console and execute the command: document.getElementById("ipt-image").files I can see the information of all files.
EDIT:
The code that I use to submit form is simple:
<form class='form-validate' action='./database/db_product.php?action=update' method='POST' enctype='multipart/form-data'>;
<input type="file" multiple class="custom-file-input" id="ipt-image" name="ipt-image[]">
<button type="submit" class="btn btn-lg btn-primary">Save</button>
</form>
I remember again that if I upload more images after this they will be added to existing ones and the $_FILES will detect all the images.

HTML Paste Clipboard File to File Input

I have a function that uploads a CSV file into a server via form submission.
It is working well, but I need to support copy and paste of CSV file from the actual file location to the input element.
I tried to do this code from a stackoverflow answer (https://stackoverflow.com/a/50427897/9751944)
const form = document.getElementById("new_document_attachment");
const fileInput = document.getElementById("document_attachment_doc");
fileInput.addEventListener('change', () => {
form.submit();
});
window.addEventListener('paste', e => {
fileInput.files = e.clipboardData.files;
});
<form id="new_document_attachment" method="post">
<div class="actions"><input type="submit" name="commit" value="Submit" /></div>
<input type="file" id="document_attachment_doc" />
</form>
It is working on images. But when I try it on CSV and other files, I am getting an error saying that the clipboard does not have any content
ie.
The first FileList and File are for the test image while the second one is for CSV

How do I add a simple image upload feature?

I want to give my new website a feature where I can upload 1 image by a button and stores(local storage) the image on another .html page, then if I grab it's absolute URL I can post this on forums websites where it's preview will show, so far I have a function that let's me upload and preview an image.. But I want to go to another level.
HTML:
<input type="file" onchange="previewFile()"><br>
<img src="" height="200" alt="Image preview...">
Javascript:
<script>
function previewFile(){
var preview = document.querySelector('img'); //selects the query named img
var file = document.querySelector('input[type=file]').files[0]; //sames as here
var reader = new FileReader();
reader.onloadend = function () {
preview.src = reader.result;
}
if (file) {
reader.readAsDataURL(file); //reads the data as a URL
} else {
preview.src = "";
}
}
previewFile(); //calls the function named previewFile()
</script>
Summary: upload image, store it(local storage), then grab it's absolute URL to paste it on another website to get the preview of that image.
Part 1: Upload
Uploading files to PHP is easy. To give the option for an user, you must add a file input to the HTML form. Here's an example:
<input type="file" name="picture" />
To make sure PHP receives the file, you must set the form method to POST and enctype to multipart/form-data
<form action="receiver.php" method="POST" enctype="multipart/form-data">
If you want to upload through javascript you might want to use AJAX. Here's an post for an example:
https://stackoverflow.com/a/6960586/3797667
Part 2: Receive (receiver.php)
The uploaded file can be accessed through $_FILES[].
Here's an example:
if(isset($_FILES['image'])){//Checks if file is set
$errors= array();
$file_name = $_FILES['image']['name'];
$file_size =$_FILES['image']['size'];
$file_tmp =$_FILES['image']['tmp_name'];
$file_type=$_FILES['image']['type'];
$file_ext=strtolower(end(explode('.',$_FILES['image']['name'])));
//(above) checks file extension by getting text after last dot
$expensions= array("jpeg","jpg","png");//supported file types
if(in_array($file_ext,$expensions)=== false){//is the extension in the supported types
$errors[]="extension not allowed, please choose a JPEG or PNG file.";
}
if($file_size > 2097152){//PHP only supports files under 2MB
$errors[]='File size must be excately 2 MB';
}
//If there's no error moves files to folder "images" in the root of this file, else prints all the errors
if(empty($errors)==true){
move_uploaded_file($file_tmp,"images/".$file_name);
echo "Success";
}else{
print_r($errors);
}
}
For more methods on file management, check this link:
http://php.net/manual/en/ref.filesystem.php
Part 3: Access
You might want to check this post if you want to get an URL for your file:
PHP Dynamically get complete Absolute URL Path for specific file that will be included in other files
If you feel like you need more info, please comment below and I'll update the post. Good luck for your project!
Sources:
http://www.tutorialspoint.com/php/php_file_uploading.htm

How to show the image uploaded using HTML file control on a new page after form submission in PHP?

I've a form which contains following file upload control and image control:
<form action="rebate_preview.php" role="form" method="post" enctype="multipart/form-data">
<input type="hidden" name="hidden_path" id="hidden_path" value="">
<input type="file" name="rebate_image" id="rebate_image">
<img id="rebate_old_image" src="#" alt="your image" width="80" height="80"/>
<button type="submit" class="btn btn-primary">Submit</button>
</form>
Here I'm enabling the user to see the preview of the image he selected for upload without actually uploading the image to server using following jQuery code :
$(document).ready(function() {
function readURL(input) {
if (input.files && input.files[0]) {
var reader = new FileReader();
reader.onload = function (e) {
$('#rebate_old_image').attr('src', e.target.result);
$('#hidden_path').val(e.target.result)
}
reader.readAsDataURL(input.files[0]);
}
}
$("#rebate_image").change(function(){
readURL(this);
});
});
Now the problems I'm facing is I'm not able to show the same image preview on the next page i.e. on a file "rebate_preview.php" after form submission using image control. The next issue I'm facing is how should I store the values from array $_FILES on the page rebate_preview.php?
Remember still the image uploaded by user is not yet uploaded to the server.
The page rebate_preview.php is just a preview page with some other fields to preview the details.
How should I show this image on the page rebate_preview.php using image control and how should I store the $_FILES array data?
I had this problem a short while back when I was building an application, the best thing to create an OBJECT URL from the selected image when you select the file, you can then set your img src to that OBJECT URL data, which will render it to the page, for example lets say you have a file input with the id image_file. you could do this:
// Preview the image on the page
$('#image_file').change(function(e) {
var selected_file = $('#image_file').get(0).files[0];
selected_file = window.URL.createObjectURL(selected_file);
$('#preview_image').attr('src' , selected_file);
});
The source is now the BLOB representation of the image, you can then submit your form to upload the image or select another image to update the preview, hope this helps :)
Simple Solution?
in PHP script just do:
print "<img src='".$_POST['hidden_path']."'>";

How to add image to multipart via javascript

I am implementing the dropzone.js file upload. However I do not want dropzone to handle the uploads because it seems like they go in bursts instead of all at once. I would like my photos to be uploaded at one time. To do so users will drag and drop photos into the dropzone area. From here they choose some custom options on the images. Then I would like a user to hit a custom button. This button can perform the following.
Add photos to multiImg[] array
invoke form
After a photo is uplaoded into the dropzone I will have access to all the information about the photo. Name, size, location(on uers computer). I am just unsure how to accomplish step 1 which is to take the photos and pass them into a form via javascript.
Is this even a good approach?
<form method="post" action="" enctype="multipart/form-data">
<input type="file" accept='image/*' name="multiImg[]" id="multiImg" />
Or possibly programatically appending
<input type="file" accept='image/*' name="Img" id="Img" />
Tags to the form and then submitting the form when done would be acceptable as well.
Can you dynamically add to the FileList for an input?
This got me closer to a solution.
xhr = new XMLHttpRequest();
formData = new FormData();
formData.append("" + paramNm + (this.uploadMult ? "[]" : ""), file, fileName);
xhr.send(formData);

Categories

Resources