Javscript upload rename file on upload with ajax and php - javascript

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);

Related

Creating PHP backend for file upload using filepond

I am creating a form on a website, where files (images and pdfs) need to be uploaded too. Until now, I have used a simple input type="file" element, coupled to a PHP file on the backend (snippet follows):
$allowed = array('jpg', 'jpeg', 'pdf', 'png');
if(isset($_FILES['uploadctl']) && $_FILES['uploadctl']['error'] == 0){
$extension = pathinfo($_FILES['uploadctl']['name'], PATHINFO_EXTENSION);
if(!in_array(strtolower($extension), $allowed)){
echo '{"status":"not_allowed"}';
exit;
}
// create folder to upload files to
$id = session_id();
$user_folder = 'user_data/' . $id;
if( is_dir($user_folder) === false ){
mkdir($user_folder);
}
if(move_uploaded_file($_FILES['uploadctl']['tmp_name'], $user_folder . "/" . $_FILES['uploadctl']['name'])){
echo '{"status":"success"}';
exit;
}
echo '{"status":"error"}';
}
This works well. However, I would like more functionality for the upload form and have looked into filepond. I created the filepond object as per the documentation and copied the boilerplate code to ./file-pond-assets, which I plan to adapt to my needs later:
<input type="file" name="uploadctl" multiple accept=".pdf,.png,.jpg,.jpeg">
<script>
const inputElement = document.querySelector('input[type="file"]');
const pond = FilePond.create( inputElement );
pond.setOptions({
server: './file-pond-assets'
});
</script>
which is showing when displaying the website. When trying to upload a file, the front-end looks fine, as an upload complete message appears. However, I cannot find the uploaded files in the tmp and uploads folder inside ./file-pond-assets. I tried changing permissions of the folders and also checked the console, but cannot find an error message. The config.php file also points to the right folders. What do I miss that makes my files not appear on my server? I would like to keep the upload as a multipart/form-data.
Here is a link to my sample file-pond PHP server implementation repository on gihtub
Repo Link: https://github.com/Onihani/filepond-php-server-example
Live Preview: http://www.ics-courses.co.uk/natbongo/filepond-php-server-example/

Send filepath to PHP using AJAX and jQuery, and get back file contents

I am trying to:
-Send a filepath to a server with post
-Have PHP on the server receive the post, and get the file contents
-Have the server respond with the file contents
I am aware that this poses some security risks. There will eventually be a system in place to prevent access to certain files depending on who is logged in. Right now im just trying to get the system to work
The JS:
function getFileContentsP(path, contents) {
$.post("/os/php/file_get_contents.php",
{"path": path},
function (data, status, jqXHR) {
contents = data;
},
);
return contents;
}
The PHP:
<?php
if ($_SERVER["REQUEST_METHOD"] == "POST") {
var $filePath = testInput($_POST["path"]);
// returns file contents
echo file_get_contents($filePath);
}
function testInput($input) {
$input = trim($input);
//$input = stripslashes($input); filepaths have slashes
$input = htmlspecialchars($input);
return $input;
}
?>
There is a file in the same directory as the php file.
Using the JS function from the console to get this file returns undefined.
This works so horribly that the file path does not even seem to reach the PHP (Discovered by using a log file that the php could write to).
Am I missing something?

PHP $_FILES does not allow audio files (wav, mp3, aiff etc) to be uploaded - but allows any other type of extension

My Problem
So I have been trying to create a simple file upload system using JavaScript (XHR) and PHP, and I have come across a problem where once the file has been uploaded to the PHP handler, it always returns that $_FILES is not set.
Code
JavaScript (on the server www.example.com):
var file = document.getElementById("fileInput").files[0];
var formData = new FormData();
formData.append("track", file);
var xhr = new XMLHttpRequest();
xhr.open("POST", "//handle.example.com/uploads.php", true);
xhr.onload = function(){
if(xhr.status == 200)
// awesome, it worked
else
return console.error("Something went wrong.");
};
xhr.send(formData);
PHP (on the server handle.example.com):
header("Access-Control-Allow-Origin: http://www.example.com", false);
if(isset($_FILES["track"])){
$file = $_FILES["track"];
$fileTemp = $file["tmp_name"];
$fileSize = filesize($fileTemp);
if($fileSize <= 150000000)
$data = "Success"; // this is returned if a file is an image file
} else
$data = "File not set."; // this is returned if a file is an audio file
echo $data;
exit;
HTML (on the server www.example.com):
<form method="post" enctype="multipart/form-data" id="ulF_uF1">
<input type="file" name="file" accept="audio/x-aiff,audio/flac,audio/mpeg,audio/ogg,audio/wav" id="fileInput">
</form>
What I've Tried
Setting the upload_max_filesize and post_max_size to 150M and 151M respectively.
Changing the name of the field name
Changing $_FILES to $_POST
None of this has worked for me, and I can't seem to find another other viable solutions relating to my problem, so all help is appreciated.
UPDATE:
After some careful testing, I realised that my upload script is actually working perfectly. What it doesn't like is the file types that are being uploaded. For some reason, PHP (version 7.2.1 at least) does not like when I upload audio files; uploading image files or PDF's work fine.
xhr.setRequestHeader("Content-Type", "multipart/form-data");
The Content-Type header for a request formatted as multipart/form-data must include a boundary parameter to tell the recipient of the message where each new bit of data starts.
By manually providing the header without it, you make the request unparsable.
Remove that line. Allow XMLHttpRequest to generate the correct content-type header for you using the FormData object.

Getting the file path of an uploaded file

I am currently doing a PHP project that requires me to make a logs of all the imported excels in the database.
I was able to get the tmp_name from the $_FILES global variable but not able to get the exact file path.
Here is my code snippet.
index.php
<form role="form" method="post" action="post_data.php" enctype="multipart/form-data">
<input type="file" name="file" required>
<button>Submit</button>
</form>
post_data.php
<?php
if ($_SERVER['REQUEST_METHOD'] === 'POST') {
//var_dump($_FILES['file']);
//var_dump($_FILES['file']['name']); #gets the file name
var_dump($_FILES['file']['tmp_name']); #gets the temp file path and name
}
?>
Any help would be much appreciated. I can also work with javascript if there are any available solutions for this problem. Thanks
You'll not get the file path. The File Upload in PHP works such that when you upload a file, it'll be uploaded to a temporary location and then your form will be posted. The path of the temporary location will be provided in tmp_name option in $_FILES array.
By using the move_uploaded_file function, this file will be moved from the temporary location to the location of your choice. But you'll have to provide the location (including the filename) where you want to move the file from temporary location.
So if you are looking for a path where you want to move the file from then it'll be present in tmp_name.
Hope this helps.
<?php
//variable containing path of Server's folder where you want to upload your file
$path;
if ($_SERVER['REQUEST_METHOD'] === 'POST') {
//var_dump($_FILES['file']);
//var_dump($_FILES['file']['name']); #gets the file name
var_dump($_FILES['file']['tmp_name']); #gets the temp file path and name
if (move_uploaded_file($_FILES['file']['tmp_name'], $path . DS . $_FILES['file']['name'])) {
//file uploaded successfully
//your file is uploaded at $path . DS . $_FILES['file']
}
else {
//error in uploading file
}
}
?>
$image=$_FILES['file'];
$base=$_SERVER['DOCUMENT_ROOT']; $filename=$_FILES['file']['name'];
$path=$base."/trial/Uploads/Original_folder/signature/".$filename."";
if(file_put_contents($path,$image)!=false)
{
echo $path;
}

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

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.

Categories