Unable to get file in $_FILES but getting in $_SERVER - javascript

(as asked by so to clarify why my question is not duplicated of suggested post )
IMHO My question is not duplicate to that question since
I am suing JavaScript and Ajax which linked question does not
though I have tried solution of that post which doesn't worked
I am using ajax and to make ajax request I am using javaScript
HTML
<input id="file" type="file" name="our-file" />
<input type="button" value="Upload" id="upload-button" />
Js
var inputFile = document.getElementById("file"),
uploadButton = document.getElementById("upload-button");
uploadButton.onclick = function () {
console.log(inputFile.files[0])
var file = inputFile.files[0];
var httpRequest = new XMLHttpRequest();
httpRequest.onreadystatechange = stateHandler;
httpRequest.open("POST", "upload.php", true);
httpRequest.setRequestHeader("X-File-Name", file.name);
httpRequest.send(file)
function stateHandler() {
var status = {
"httpRequest ready state": httpRequest.readyState,
"status": httpRequest.status,
"httpRequest responseText":httpRequest.responseText
};
console.log(status);
console.log(httpRequest.responseText);
}
}
now when I try to get uploaded file via $_FILES I get empty array but
$_SERVER have complete file information, is it because I have only sent header not file itself ?
screeshot of my output with $_SERVER http://i.stack.imgur.com/1GMdh.png
screen shot of my output with $_FILES http://i.stack.imgur.com/IECUt.png
thanks and I don't want jquery suggestion (I think its good to know language before framework developed by it :)

You are sending raw file data. You aren't sending a multipart/form-data encoded request, so it won't be processed as regular form data (so $_FILES and $_POST won't be populated).
Create a form data object.
var formData = new FormData();
Put the file information in that:
formData.append("myFile", inputFile.files[0]);
Send that:
request.send(formData);

Related

$_FILES empty after AJAX upload

I'm developing a simple script to upload a file through AJAX but after form submission, the variable $_FILES is completely empty, although the file exists within php://input, but with no simple way to extract only the file. Anyone knows the reason and/or solution to this problem?
I've checked all the common solutions.
enctype="multipart/form-data"
rights to temp folder
form-tags closing
doublequotations
and the output of the file-input in JS
Nothing has solved my problem.
RED
This is NOT jquery, and I haven't found a duplicate in 24h. So please don't mark as duplicate unless you're sure it is one.
HTML
<form action="upload.php" method="POST" enctype="multipart/form-data" id="testf">
<input type="file" name="file" accept=".jpg">
<input type="submit" value="Skicka">
</form>
JavaScript
let data = document.querySelector("#testf");
data.onsubmit = function() {
var http = new XMLHttpRequest();
http.open("upload.php", data.action);
http.onreadystatechange = function () {
console.log(http.response);
}
http.setRequestHeader("Content-type", data.enctype);
http.send(new FormData(data));
event.preventDefault();
return false;
}
PHP
<?php
var_dump($_FILES);
?>
This should print the contents of my file, but
array(0) {}
is all I get.
Request payload is:
------WebKitFormBoundaryZVGq8suqFUUSFDtW
Content-Disposition: form-data; name="file"; filename="david.jpg"
Content-Type: image/jpeg
------WebKitFormBoundaryZVGq8suqFUUSFDtW--
You have a problem with your JavaScript method XMLHttpReqest. It takes at least two parameters: Method and url.
Full parameters are:method, url, async, user, password
Change your code from:
http.open("upload.php", data.action);
To:
http.open("post", data.action );
Update:
Also remove
http.setRequestHeader("content-type", "multipart/form-data")
Form data already sets its headers for content-type.
Did you checked if memory limit is set to -1 or high enough in php.
Sometime on Apache or iis server, there is also a block on high file uploads.

Reading JavaScript Variables in PHP

I am looking for a way to either read an image src in PHP or read a JavaScript variable in PHP.
The plan:
I have a webcam script in JavaScript that takes an image using the base64 Canvas method, but I need it to update a MySQL record using PHP.
After trying many methods; cookies, submit forms, ajax. I decided that making a post here was the best idea.
(!) Use with caution. This is a proof of concept. In PHP you should never just accept and compute client-side data without checking it for malicious code and sanitizing the input. (!)
You could send it to PHP using AJAX by putting your base64-source into formData.
Javascript:
// ajax.js
var xhr = new XMLHttpRequest(); // initialize a new XHR
var formData = new FormData(); // initialize form data
var myFile = 'data:image/png;base64,iVBORw0KGgoAAAANSUhEUgAAASwAAACWCAYAAABkW7XSAAAEaElEQVR4Xu3UgQkAMAwCwXb/oS10i4fLBHIG77YdR4AAgYDANViBlkQkQOALGCyPQIBARsBgZaoSlAABg+UHCBDICBisTFWCEiBgsPwAAQIZAYOVqUpQAgQMlh8gQCAjYLAyVQlKgIDB8gMECGQEDFamKkEJEDBYfoAAgYyAwcpUJSgBAgbLDxAgkBEwWJmqBCVAwGD5AQIEMgIGK1OVoAQIGCw/QIBARsBgZaoSlAABg+U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VoAQIGCw/QIBARsBgZaoSlAABg+UHCBDICBisTFWCEiBgsPwAAQIZAYOVqUpQAgQMlh8gQCAjYLAyVQlKgIDB8gMECGQEDFamKkEJEDBYfoAAgYyAwcpUJSgBAgbLDxAgkBEwWJmqBCVAwGD5AQIEMgIGK1OVoAQIGCw/QIBARsBgZaoSlAABg+UHCBDICBisTFWCEiDwAIGUVl1ZhH69AAAAAElFTkSuQmCC';
xhr.open('POST', '/requestHandler.php') // init your request
xhr.onreadystatechange = function () {
// check if the server was able to compute the XHR
if(xhr.readyState === XMLHttpRequest.DONE && xhr.status === 200) {
// handle the response
console.log(xhr.responseText) // log the PHP output
}
}
// a form data element needs a descriptor/name and a value.
formData.append('myfile', myFile);
xhr.send(formData); // send your xhr to the server
PHP:
// requestHandler.php
<?php
if('$_POST') {
echo $_POST['myfile']; // this is your image source
}
Further information:
XMLHttpRequest
FormData
PHP $_POST

Storing information from php script

I m working on an html page that contains a form allowing users to enter their informations and upload files. all informations will be inserted in Mysql database.
in Javascript, im using XMLHttpRequest to send the files to the server and "upload.php" to rename (to avoid dupplicated names) and move them in the upload directory.
For better user experience, this will be done before submitting the whole form.
My question is : How can i store the new filenames (defined in upload.php)to use them in the form submission "submit.php"?
the reason for this is that in "submit.php", i insert first the user informations in "user" table and then select the "user_id" (auto increment) that will be inserted with filenames in the "files" table.
Could php sessions be an approach to do this ? is there another way? Thanks for your help
html:
<form action="submit.php" method="post" id="submitform">
<div>
<--!user info part1-->
</div>
<div id="filesContainer" class="eltContainer">
<input type="file" id="filesList" multiple>
</div>
<div>
<--!user info part2-->
</div>
javascript:
var fd = new FormData()
var xhr = new XMLHttpRequest()
for (var i=0,nb = fichiers.length; i<nb; i++) {
var fichier = fichiers[i]
fd.append(fichier.name,fichier)
}
xhr.open('POST', 'upload.php', true)
upload.php :
<?php
foreach($_FILES as $file){
$filename = date('Y') . date('m') . date('d') . date('H') . date('i') . basename($_FILES[$file]['name']);
move_uploaded_file( $file['tmp_name'],"../upload_dir/" .$filename);
}
exit;
I would consider using something like md5 for unique filenames.
Nevertheless you can push filenames into some array, and than return those filenames, as a result of post request, and put them back into some input field.
To retrieve the response simply add this lines to your code below open
xhr.onreadystatechange = function {
// If the request completed and status is OK
if (req.readyState == 4 && req.status == 200) {
// keep in mind that fileNames here are JSON string
// as you should call json_encode($arrayOfFilenames)
// in your php script (upload.php)
var fileNames = xhr.responseText;
}
}
If you'd like consider using a simple library for AJAX requests, like axios. It's promise based HTTP client for the browser, really simple to use and saves you some time and effort cause you don't have to memorize all this stuff you and I have just written.
This is one approach, but I think you can use $_SESSION as well, and it's perfectly valid. My guess is you don't have logged in user at this point, so my idea is as follows:
put filenames into the $_SESSION
use db transactions - as #Marc B suggested - to connect files with
user
if there were no errors just remove filenames from $_SESSION, if there was some, just redirect the user back to the form (possibly with some info what went wrong), and this way he doesn't have to reupload files, cause you have filenames still in $_SESSION

Store image on server with html/javascript/mongodb

I want to upload an image from a user to the server. With the all path, it works (I can store on MongoDB). But with <input id ='image_upload' type='file' name='image_upload' />, it doesn't works (security, no full path)
So I want to know if there is an other way to do that. Maybe asolution where I store directly on the server will be ok (Using javascript, html, ajax, ... )
Thank you
You can use form data as such:
https://developer.mozilla.org/en-US/docs/Web/API/FormData/Using_FormData_Objects
Paticularly,
var formData = new FormData();
// HTML file input, chosen by user
formData.append("userfile", fileInputElement.files[0]);

uploading pdf/doc etc and sending data to the server in request - Javascript

I need to upload pdf,excelsheets,doc. etc format to server - data in request file using simple Javascript.
I was thinking to do with Blob , byte stream .. is it possible.
Can someone explain ?
Using vanilla Javascript you can create an XMLHTTPRequest object and send the file to any endpoint of your choice.
Some questions to consider when you are working doing this:
Are you looking to upload just the file or do you need to upload any associated data with it?
Do I need to support multiple files? If so, you could use the FormData object (it is a defined key value pair type) to hold multiple files if you have an HTML5 input form with the multiple attribute set. Make sure your project allows support for it.
What server/framework are you using? How do you access this? A request object? Something similar?
How do you want/need to create a selector for your html file input for use with Javascript? I'll provide an example of using the html attribute of id below.
Do you need to support CORS? Essentially, are you sending a request to the same server or a remote server? If remote, you'll need to configure CORS in your server.
file input that allows multiple file support
<input type='file' id='multiple-file-input' multiple>
javascript example
// idElementForFiles - id of the <input type="file" multiple>
// endpoint - URL to send your request to
var idElementForFiles = 'multiple-file-input';
var endpoint = '/path_to_server/request';
var formdata = new FormData(); // Create FormData
var uploadedFiles = document.getElementById(idElementForFiles); // set our uploadedFiles variable
// Iterate through each file in uploadedFiles
for (i = 0; i < uploadedFiles.files.length; i++) {
// Appending each file to FormData object
// sending to 'endpoint' as an array of {'name_of_file': 'binary_file_data'}
formdata.append(uploadedFiles.files[i].name, uploadedFiles.files[i]);
}
// create new Ajax call and send
var xhr = new XMLHttpRequest();
xhr.open('POST', endpoint);
xhr.send(formdata);
xhr.onreadystatechange = function () {
if (xhr.readyState == 4 && xhr.status == 200) {
console.log(xhr); // log response object
}
}

Categories

Resources