How to add image to multipart via javascript - 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);

Related

Sending multiple file input fields programmatically in one form

I'm trying to use the blueimp/jQuery-File-Upload plugin to programmatically send more than one file input field though the same form.
When user select form files, it just append them in a JS variable to further send them with $('#form').fileupload('send') method on form submission. My goal is to use the exactly same synchronous form I was using before in an asynchronous way. So when user click on form submit button, it prevents default action and them let the plugin to do the task, sending all form data and displaying overall upload progress.
I'm mainly following these guides:
https://github.com/blueimp/jQuery-File-Upload/wiki/API
https://github.com/blueimp/jQuery-File-Upload/wiki/Multiple-File-Input-Fields-in-One-Form
Actually it's almost working, but it does not send more than one input file to the server end. In fileuploadadd event I'm pushing data.files[0] (my file inputs are single file only, but each of them use different accept attributes) to a "global" uploadable array and then on form submission I use something like $('#form').fileupload('send', {files: uploadable}).
I guess I'm not doing it the right way, since only one file is being sent along with form data. What is the correct way to programmatically send more than one file input file using a single form?
I'm also not too confident about overall upload progress... If I use fileuploadprogressall event to read the upload progress will it be reporting the progress of all uploaded files?
JS (simplified)
$(function () {
var uploadable = [];
$('#form').fileupload({
autoUpload: false,
singleFileUploads: false,
add: function (event, data) {
uploadable.push(data.files[0]);
return false;
},
// other event callbacks
})
.prop('disabled', !$.support.fileInput)
.parent().addClass($.support.fileInput ? undefined : 'disabled');
$('#form').submit(function (event) {
event.preventDefault();
$('#form').fileupload('send', {files: uploadable});
});
});
HTML
<form id="form" action="upload" method="post" enctype="multipart/form-data">
<!-- other text/hidden inputs that will also be sent -->
<input type="file" name="image" id="image" accept="image/*" />
<input type="file" name="video" id="video" accept="video/*" />
</form>
uploadable.push(data.files[0])
You vividly told the compiler to only push the first file.
Have you tried using foreach and push all files?
Thank you,

Show loading image while its uploading?

I have an image upload form, which auto uploads the image when user selects the file.
Upload form
<form id="imageupload" action="./uploadres.php" enctype="multipart/form-data" method="post">
<input type="file" name="file" value="Ekle" accept="image/*" size="20">
</form>
Auto upload script when user selected file
$("input[name='file']").change(function() {
this.form.submit();
});
Show/hide loading image function:
$('#loadimg').show();
$('#contents').load(function(){
$('#loadimg').hide();
});
What I am trying to do is showing loading image while its uploading. What is the correct way to integrate the Show/hide loading image method into my form submit ?
If you are doing a full HTML post, then you only have one option:
Using the form's onsubmit event to display the uploading symbol. This will be cleared when the new HTML is downloaded.
On the other hand, if you are using jQuery to submit the form, there are a several excellent ways to handle that.
I'd point you to this discussion for an overview.

Use Fluentlenium to upload a file in dropzone.js

I'm looking to write a test to upload a file using Fluentlenium and DropZone.js (http://www.dropzonejs.com/). Dropzone.js works in a modal and then you can drag and drop or upload the normal way.
As soon as you click to upload the test crashes because your no longer in the browser.
I've found many posts getting this to work in Selenium using things like:
WebElement fileInput = driver.findElement(By.xpath("//input[#type='file']"));
fileInput.sendKeys("C:/path/to/file.jpg");
I however cannot sendKeys to anything because their isn't even an input type="file" when using DropZone.js.
The only input types I'm seeing are all type hidden.
<input type="hidden" name="key" value="temp/${filename}">
<input type="hidden" name="AWSAccessKeyId" value="secret">
<input type="hidden" name="acl" value="private">
<input type="hidden" name="success_action_redirect" value="">
<input type="hidden" name="policy" value="secret=">
<input type="hidden" name="signature" value="secret">
<input type="hidden" name="Content-Type" value="application">
We're also using Amazon Web Server to upload the documents too, it seems like everything is working off the below script:
<script id="hiddenKeyPairs" type="text/javascript">
var hiddenKeyPairs = {
key: 'temp/${filename}',
AWSAccessKeyId: 'secret',
acl: 'private',
"success_action_redirect": '',
policy: 'secret',
signature: 'secret/secret',
"Content-Type": 'application'
};
var formAction = 'https://secret.com/';
</script>
Which is located on my page.
I'm not seeing anything helpful on https://github.com/FluentLenium/FluentLenium#driver for this.
Do I need to somehow send the file to the key hash in the above script?
Any thoughts?
I'm not sure about the AWS part but I've a similar question about file upload (Programmatically upload / add file via Dropzone e.g. by Selenium), and some potential solutions. I feel they are not very robust, but basically:
Approach 1: Use Java Robot to simulate the GUI actions -
// this opens the file browser window
driver.findElement(By.id("uploadDropzone")).click();
// put the file path in clipboard, paste (C-V) to the window, enter.
StringSelection ss = new StringSelection("some file path");
Toolkit.getDefaultToolkit().getSystemClipboard().setContents(ss, null);
Robot robot = new Robot();
Thread.sleep(2000);
robot.keyPress(KeyEvent.VK_CONTROL);
robot.keyPress(KeyEvent.VK_V);
robot.keyRelease(KeyEvent.VK_V);
robot.keyRelease(KeyEvent.VK_CONTROL);
Thread.sleep(5000); // need some wait for GUI action to work...
robot.keyPress(KeyEvent.VK_ENTER);
robot.keyRelease(KeyEvent.VK_ENTER)
Approach 2: Do all in code (hacky...) - yes there is a file input element, but only defined in Dropzone.js itself, which can be selected with $(".dz-hidden-input"). But you also have to make it visible (as Selenium can only act on visible elements), then can call sendKeys on it. And after that, again in Javascript, retrieve the File object from that element, then pass to addFile(file) on the Dropzone object.

How to reference to an uploaded img src in HTML

I am creating a responsive mobile website, and I want to be able to take and then upload a picture from the device. I have got this part working using
<form method="post" action="takephoto.php" enctype="multipart/form-data">
<input type="file" id="myfile" name="myfile" accept="image/*;capture=camera"/>
</form>
Now, what I am having trouble with is, after I have selected the picture that I want to use I do not know how to reference it later in my code. The reason I need to is I am using a .js library which allows me to upload a picture of a ISBN barcode and the .js file will read this file and spit out the ISBN as text which I will do more with later. (maybe link this to a Google Books API)
This is where I am getting the barcode scanner .js from: http://badassjs.com/post/654334959/barcode-scanning-in-javascript
I am relatively new to all of this, thanks for your help.
You will have to use ajax. This link contains some useful information for you.
Use ajax to get the picture uploaded and in the response, return the url or "failed". Then you can use in your js code,
if(response=="failed"){
//Handle upload failed
}
else {
//Handle url. Here response is your url actually.
// So to append the image to a given id, you would use,
$("#append_to_id").append("<img src='"+response+"'>");
}
Since the JavaScript library you are using is parsing an image on the page,
you have to show the image on the page after you have uploaded it.
So basically you need 4 steps to achieve this:
show an upload form (This is what you have done in the question);
grab the image uploaded in step 1 and save it to an accessible place
display the image on the screen
call get_barcode_from_image.js to parse it
Here's a piece of code for reference. It contains all the 4 steps above.
<?php
// step 2: save the image
if ($_FILES['myfile']['error'] == 0) {
move_uploaded_file($_FILES['myfile']['tmp_name'], 'u/barcode.jpg');
?>
<!-- step 3: show the image -->
<img src="u/barcode.jpg" id="barcode">
<script src="get_barcode_from_image.js"></script>
<div id="result"></div>
<!-- step 4: parse the barcode -->
<button onclick='document.getElementById("result").innerHTML = getBarcodeFromImage("barcode")'>scan</button>
<?php
}
?>
<!-- step 1: show the upload form -->
<form method="post" action="barcode.php" enctype="multipart/form-data">
<input type="hidden" name='a' value='b'/>
<input type="file" id="myfile" name="myfile" accept="image/*;capture=camera"/>
<input type="submit" value="submit" />
</form>
Of course you can use ajax or so to get better user experience, but the process won't change.

Upload files without refreshing the page by using ajax post

I have a page file-upload.jsp with the code snippet below:
<form action="" id="frmupload" name="frmupload" method="post" enctype="multipart/form-data">
<input type="file" id="upload_file" name="upload_file" multiple="" />
<input type="submit" value="Update" />
</form>
I have 2 questions:
The moment I select some files, i.e the onchange event of the input type file, the file(s) should get uploaded.
I have a Java page that receives multipart request parameter and uploads the file to the said location. My problem is the form submission onchange, so that the Java file can proceed with further operations.
I googled and went through lot of articles. Some say it's not possible to upload files directly via Ajax, some say submit the form to an iframe via Ajax/jQuery.
I tried a lot of code from internet, such as this:
$(document).ready(function(){
$('upload_file').change(function(){
var data = new FormData();
data.append('file', $(this[0].files[0]));
$.ajax({
url: 'photo.jsp',
type: 'post',
contentType: attr('enctype', "multipart/form-data"),
data: data,
success: function(data){
alert(data);
}
})
});
});
but could not get the expected results.
I also need a progress bar for the upload operation.
Look at this example using an IFrame, is in PHP but changing the action should do the trick
Ajax Style File Uploading Using Hidden IFrame
Since you're already using jQuery, I would definitely go for the jQuery Form Plugin, which allows you to do form uploads via AJAX, even if the form contains a file input.
There is an example on its website available that shows how to display a progress bar.
Look at this example it is exact as you want
http://www.asp.net/ajaxlibrary/ajaxcontroltoolkitsamplesite/asyncfileupload/asyncfileupload.aspx

Categories

Resources