Problem with Drag and Drop file upload using PHP server script - javascript

I'm trying to upload files using PHP script on the server as the upload handler. It works just fine with a traditional web form like this:
<form action="uploadHandler.php" method="post" enctype="multipart/form-data">
Select image to upload:
<input type="file" name="fileToUpload" id="fileToUpload">
<input type="submit" value="Upload Image" name="submit">
</form>
But when I try to switch to a drag-and-drop form the PHP handler is failing with an undefined index on the name value "fileToUpload". Here is the error message:
PHP Notice: Undefined index: fileToUpload in /home/...../uploadHandler.php on line 10
Line 10 of uploadHandler.php contains this statement:
$fileName = $_FILES['fileToUpload']['name'];
I'm still using the name=fileToUpload in my drag and drop form:
<form class="my-form">
<p>Upload multiple files with the file dialog or by dragging and dropping images onto the dashed region</p>
<input type="file" id="fileToUpload" name="fileToUpload" onchange="handleFiles(this.files)">
<label class="button" for="fileElem">Select some files</label>
</form>
This is the function on the page that contains the drag and drop form that calls the uploadHandler:
function uploadFile(file, i) {
var url = 'https://xxxxxx/uploadHandler.php'
var xhr = new XMLHttpRequest()
var formData = new FormData()
xhr.open('POST', url, true)
xhr.setRequestHeader('X-Requested-With', 'XMLHttpRequest')
formData.append('file', file)
xhr.send(formData)
}
I tried adding something like formData.append('name', 'fileToUpload') before calling xhr.send, but that didn't seem to help.
What am I missing?

Related

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

Form's uploaded file disappears on canceling new selection of file

I have a simple form on my webpage.
<form action="upload.php" method="post" enctype="multipart/form-data">
Select image to upload:
<input id="browse" type="file" name="fileToUpload" id="fileToUpload">
<input type="submit" value="Upload Image" name="submit">
</form>
Now, my problem is when I browse and choose file to upload it shows which file I am going to upload.
But when I click on Choose file and browse again and this time if I change my mind mid way and hit cancel then old selected image also goes away.
On canceling it removes already selected image also.
Why does this happen and what to do if I want my old selected image to be selected after browsing again and canceling?
Thanks in advance!
Thanks to #Carlos , added this javascript
var input = document.getElementById("browse");
var selectedFile;
input.addEventListener('change', updateImageDisplay);
function updateImageDisplay() {
if(input.files.length==0) {
input.files = selectedFile;
}
else {
selectedFile = input.files;
}
}
and now it works fine! you can check here.

upload base64 image data to Amazon S3

Alright, in this phonegap app I start with a huge image file from the device's camera.
Then I reduce the resolution and allow the user to crop it using javascript canvas and some very cool code called darkroomJS.
At the end darkroomJS uses toDataURL() method to get base64 data out of the canvas.
Now I need to upload it to Amazon S3.
I can upload a file from my computer to S3 using a form just fine. What I'm working on is sending the base64 data.
I also have a function that converts the base64 data into a blob. (which I've read will be required, but I'm open to other ideas).
<form action="https://mybucketname.s3.amazonaws.com/" method="post" enctype="multipart/form-data">
<input type="" id="key" name="key" value="uploads/${filename}">
<input type="" id="AWSAccessKeyId" name="AWSAccessKeyId" value="YOUR_AWS_ACCESS_KEY">
<input type="" id="acl" name="acl" value="private">
<!-- <input type="" id="success_action_redirect" name="success_action_redirect" value="http://localhost/"> -->
<input type="" id="policy" name="policy" value="YOUR_POLICY_DOCUMENT_BASE64_ENCODED">
<input type="" id="signature" name="signature" value="YOUR_CALCULATED_SIGNATURE">
<input type="" id="Content-Type" name="Content-Type" value="image/jpeg">
<!-- <input id="file" name="file" > -->
<br>
<input type="submit" value="Upload File to S3">
</form>
I write in the credentials using jquery after they are obtained from my server. That part works fine.
The trouble is how do I put a blob in the form?
I've tried two methods.
Setting the value with jQuery.
$page.find("#file").attr('value', blobData);
//inserts the string [object Blob] text into the field and ships it to S3, not very useful
also I've tried:
var fd = new FormData(document.forms[0]);
fd.append('file', blobData);
//has no effect; S3 then complains that it was expecting a file, and didn't get one.
What am I doing wrong? How can I make this work?
Alright, got something that works:
I guess having the form actually rendered on the page kinda forces the browser to stringify the blob.
The function s3Man.getS3Policy just makes a AJAX request to my sever to get a signed s3 policy, keys, etc.
this.uploadBase64ImgToS3 = function(base64Data, filename, callback){
var xmlhttp = new XMLHttpRequest();
var blobData = dataURItoBlob(base64Data);
var contentType = false;
if (filename.match(/.png/)) var contentType = 'image/png';
if (filename.match(/.jpg/)) contentType = 'image/jpeg';
if (!contentType){
xStat.rec("content type not determined, use suffix .png or .jpg");
return;
}
s3Man.getS3Policy(filename, function(s3Pkg){
console.log("policy:", s3Pkg);
var fd = new FormData();
fd.append('key', s3Pkg.filename);
fd.append('acl', 'public-read');
fd.append('Content-Type', contentType);
fd.append('AWSAccessKeyId', s3Pkg.awsKey);
fd.append('policy', s3Pkg.policy);
fd.append('signature', s3Pkg.signature);
fd.append("file", blobData);
xmlhttp.open('POST', 'https://swoopuploadspublic.s3.amazonaws.com/', true);
xmlhttp.send(fd);
});
}

upload a file without having the submit button in mvc

I want to upload a file without using the submit button. The file must be uploaded at the moment the user picks it from browse file window.
Now please do provide some ajax code or some jquery to upload the file and also how to delete the file.
Please provide the control view for this.
View>>>
<form action="FileUploadPost" method="post" enctype="multipart/form-data">
<label for="file1">Filename1:</label>
<input type="file" name="files" id="file3" />
<label for="file2">Filename2:</label>
<input type="file" name="files" id="file4" />
</form>
Controller>>>
[HttpPost]
public ActionResult Index(IEnumerable<HttpPostedFileBase> files)
{
foreach (var file in files)
{
if (file.ContentLength > 0)
{
var fileName = Path.GetFileName(file.FileName);
var path = Path.Combine(HttpContext.Server.MapPath("~/App_Data/Uploads"), fileName);
file.SaveAs(path);
}
}
return RedirectToAction("Index");
}
You can use JQuery file uploader control for your requirements.
It provides functionality to upload file with both "By Clicking on the button" and "Auto Upload".
Auto Upload : This functionality will upload file as soon as you select the file.
See Ajax File Upload for step by step implementation.

Making function work for any one of the same type of element

I am trying to create a file upload system. This file upload system works great for the mosot part. The problem comes in because there are multiple HTML elements on the page that have class file and multiple HTML elements that are upload-buttons. Right now file uploading works great only for the first HTML element that contains the upload text field and upload button only, all others fail to work (due to Javascript selecting the [0] object every time).
My question is, how can can I adjust the function below to cater to whatever upload container / button that was used?
Essentially what needs to happen is, if the user clicks on the nth upload button the functions array slots needs to be equal to n-1 somehow.
I appreciate any assistance with this problem.
Many thanks in advance!
$(document).on('click','.upload-button', function(){
var data = new FormData();
jQuery.each($('.file')[0].files, function(i, file) {
data.append('file-'+i, file);
});
//Some more code...
});
HTML
<div class="input-text-field">
<input name="userfile" class="file" type="file" />
<input class="submit upload-button" type="submit" value="Upload" />
</div>
Use prev() to target just the previous .file element, and be aware that your code does'nt have a .file element, it has a #file element, and multiple ID's are invalid.
$(document).on('click','.upload-button', function(){
var data = new FormData();
jQuery.each($(this).prev('.file')[0].files, function(i, file) {
data.append('file-'+i, file);
});
//Some more code...
});
html
<div class="input-text-field">
<input name="userfile" class="file" type="file" />
<input class="submit upload-button" type="submit" value="Upload" />
</div>

Categories

Resources