PHP / AJAX - Access javascript file array with $_FILES in PHP - javascript

I have this as HTML:
<input type="file" id="foo" multiple/>
This javascript:
$("#foo").change(function(){
var files = $(this)[0].files;
$.ajax({
// ???
});
});
This PHP (upload.php):
if (!empty($_FILES)) {
// Upload code
Currently the files are being read correctly from the input box.
I want to use these files inside the upload.php. I have a different dropzone on my page which uses this upload.php. I don't want to write unneccesary double code so I would like to use this file again. However, I cannot send an ajax request with $_FILES.
TL;DR: How can I send an array with files with ajax to a PHP Url and use it there with $_FILES ?
Notes:
+ My input is not in a < form >
+ It is possible to select multiple files, so I need to pass multiple files to the php file
Thanks in advance!

You could try something like this:
var formData = new FormData();
for (var i = 0; i < files.length; i++) {
var file = files[i];
formData.append('files[]', file, file.name);
}
$.post( 'somewhere', formData, callback);
Not the exact code, but it should get you started.

Related

Javscript upload rename file on upload with ajax and php

This question has been asked many times, but I can't find the right answer.
I'm trying to upload a file with javascript, ajax and php. Which works so far. However, I would like to rename the file when uploading and in javascript, so that I can determine the name of the file from there.
my function to upload the file via ajax in javascript
async function uploadFile() {
let formData = new FormData();
formData.append("file", fImage.files[0]);
await fetch('/upload.php', {
method: "POST",
body: formData
});
alert('The file has been uploaded successfully.');
}
my input field in html
<input class="form-control" type="file" id="fImage">
my upload.php
<?php
/* Get the name of the uploaded file */
$filename = $_FILES['file']['name'];
/* Choose where to save the uploaded file */
$location = "upload/".$filename;
/* Save the uploaded file to the local filesystem */
if ( move_uploaded_file($_FILES['file']['tmp_name'], $location) ) {
echo 'Success';
} else {
echo 'Failure';
}
?>
The aim would be to determine the file name via javascript, e.g. via a variable
you can use the 3rd parameter of append to specify the filename (MDN)
formData.append("file", fImage.files[0], new_name);

Send file to PHP server with JS

I can send files from the browser to the server using drag'n'drop and this code simply works fine:
var temp = new FormData();
temp.append("file_content",e.originalEvent.dataTransfer.files[0]);
//Ajax POST here...
Then I make a POST request (Ajax) to send that file to PHP and PHP can manipulate that file using $_FILES[file_content]. Easy.
My problem is that sometimes the user drops a folder and I already can manipulate the files inside that folder with JS in order to send them via Ajax. My problem is that PHP cant manipulate the $_FILE anymore, it is empty. My code:
var reader = entry.createReader();
reader.readEntries(function(entries) {
entries.forEach(function(dir,key) {
if (dir.isFile) {
var temp = new FormData();
temp.append("file_content",dir);
//Ajax POST here...
}
});
});
So I need someway to convert dir (which is of type FileEntry) to type File (e.originalEvent.dataTransfer.files[0]). How can I do this?

JS / HTML Adding params to a given filelist for a file upload

For a file upload I collect multiple files :
<input type="file" multiple onchange="uploadFiles(this)" id="fd" />
In the JS function uploadFiles() I retrieve each file and append it to a formData object :
function uploadFiles(e) {
var fileList = document.getElementById(e.id).files;
var fd = new FormData();
for (var i = 0; i < fileList.length; i++) {
var file = fileList[i];
fd.append('files[]', file, file.name);
}
}
Finally I upload it via AJAX to a server.
Each file object contains 4 key/value parameter with the key: name, LastModified, webkitRelativePath and size.
On the server side I need additional information per file (description from a user) which I want to send with the same upload process. My question is :
Is it possible to add params to the file object so I can retrieve them which each file on the server side ?
If not, how to bind additional parameters to each appended file object in the FormData object ?
Any hints are welcome. Info: I use pure JS only.

javascript read from a txt file and inject text into form

I apologize in the advance as I am a total beginner.
I have a pre-existing html form with text fields. I need to have a button that will allow me to upload a txt file (since when trying to look for answer about this, I learned javascript can't just access a file from my PC without me actively uploading it). Then I need the values from this txt file inserted into the text fields (for example, the form has: name, last name, phone etc - and the file will fill out this info).
I am going crazy trying to collect bits and pieces from other people's questions. any help would be greatly appreciated!
it depends on how you would like to have this handled, there are basically two options:
File Upload and page redirect
you could provide a file upload form to upload your textfile, redirect to the same page via form submission, handle the data on serverside (e.g. parse the file and get the values out of it) and let the server inject the values as default properties for the form file which is returned to the browser
XMLHttpRequest File Upload
in modern browsers, the native xhr object supports an upload property, so you could send the file via that upload property. it has to be sent to a serverside script that parses the file and returns the values in a fitting format, e.g. json (which would look like this: {'name':'somename', 'lastName':'someothername'}). then you have to register an eventlistener on completion of this upload (e.g. onload) and set these values on javascript side.
check this out for XMLHttpRequest upload (better solution in my opinion): https://developer.mozilla.org/en-US/docs/Web/API/XMLHttpRequest/Using_XMLHttpRequest#Submitting_forms_and_uploading_files
edit:
well, the easiest solution would be just to provide a textfield and paste the content of the file into this field, hit a button and the content is parsed. then you wouldn't rely on network traffic or even a serverside handling, but could do everything with javascript, e.g. like this:
dom:
<textarea id="tf"></textarea>
<button id="parse">fill form!</button>
js:
var tf = document.getElementById("tf");
document.getElementById("parse").addEventListener("click", function(){
var formData = JSON.parse(tf.value);
//if your textfile is in json format, the formData object now has all values
});
edit: from the link i posted in the comments:
<!-- The HTML -->
<input id="the-file" name="file" type="file">
<button id="sendfile">send</button>
and
document.getElementById('sendfile').addEventListener("click", function(){
var fileInput = document.getElementById('the-file');
var file = fileInput.files[0];
var formData = new FormData();
formData.append('file', file);
var xhr = new XMLHttpRequest();
// Add any event handlers here...
xhr.open('POST', '/upload/path', true);
xhr.onreadystatechange = function(){
if(xhr.readyState == 4 && xhr.status == 200){
var values = JSON.parse(xhr.responseText);
//these are your input elements you want to fill!
formNameInput.setAttribute('value', values.name);
formFirstNameInput.setAttribute('value', values.firstName);
}
}
xhr.send(formData);
});
as already said, your serverside has to parse the file and respond with json

Drag and Drop File Uploading

I am using file uploading in my web application by using the <input type="file" /> html tag. My feature works well with choosing a file from the file chooser and submitting the file, however now I want to upload a file on drag and drop events i.e. the user drags a file from some location on his computer and when he drops it in a particular section in my web page, the file starts uploading.
Until now I managed to read the files from the drop event by
function drop(evt)
{
evt.stopPropogation();
evt.preventDefault();
if (containsFiles(evt))
{
var files = evt.dataTransfer.files;
var count = files.length;
// Only call the handler if 1 or more files was dropped.
if (count > 0)
// upload files
}
}
}
but how can I upload these files? I can't change the value of input type = file for security reasons. So what can I do to pass these files to my servlet?
You have to use FormData (beware of IE support).
When drop happens you need to create FormData object, and append data into it, then POST that form to your url. It is asynchronous method and will not reload your page.
function drop(evt) {
evt.stopPropogation();
evt.preventDefault();
var files = evt.dataTransfer.files;
if (files.length > 0) {
var form = new FormData();
for(var i = 0; i < files.length; ++i) {
var file = evt.dataTransfer.files[i];
form.append('image_' + i, file, file.name);
}
var req = new XMLHttpRequest();
req.open('POST', '/pathToPostData', true);
req.onload = function(evt) {
console.log(req.responseText);
}
req.send(form);
}
}
Beware that I've tested it only in Chrome and Firefox, IE9 probably will not work but IE10 should, if you test it, let us know please.
I believe you want something in the likes to Dropzone.js
I haven't tried it yet, but it's a library that allows for easy drag-and-drop of files to a website that is running it, v3.0 comes without the need to use jQuery.

Categories