Files cannot read by my Ajax after reading - javascript

im using an API to pass a whole form including images, textarea, etc.
it uses new FormData($('#form')) to pass the data into server.
everything went smooth except when i did something on <input type="file" id="upload"/>
I made the input to show the image every time the user uploads a new photo.
$(function() {
$("#upload").on("change", function()
{
var files = !!this.files ? this.files : [];
if (!files.length || !window.FileReader) return; // no file selected, or no FileReader support
if (/^image/.test( files[0].type)){ // only image file
var reader = new FileReader(); // instance of the FileReader
reader.readAsDataURL(files[0]); // read the local file
reader.onloadend = function(){ // set image data as background of div
//Showing the images here..
}
}
});
});
But now, when im submitting the form again using Ajax, it cannot read or pass the image. No image passed in the database.
Whenever i comment the line //var files = !!this.files ? this.files : []; its back to normal, but the image is not showing.
i want to ask is there an alternate way to show the image without affecting the <input type="file" tag?
Or if i have to create another <input type="file" with style="display: none;", how can i pass the image from one input with type="file" to another input with also type="file"?

Related

How to upload image to firebase cloud storage from input field?

I have an input field, where users can choose what image they want to upload, and then I need to send to cloud storage. The problem is, I don't know how to get the file they selected. I saw a lot questions like this, this, this, etc. Most of the questions I saw, like this one, are asking for previewing the images BEFORE uploading. I don't think I need to preview the image, i just want to upload it. How do I do this? Here is my current code:
function addImage() {
$("#addImage").append('\
<input type="file" id="image" accept="image/*">\
<button type="submit">ok</button>\
<button onclick="cancelAddImage()">cancel</button>');
$("#addImage").submit(function() {
var image = $("#image").files;
console.log(image);
storage.ref("images").put(image).then(function(snapshot) {
console.log('Uploaded a file!');
});
});
}
The console.log() for this is giving "undefined". I also tried .files[0] instead of .files;, and many others.
In your html code, you place the input field with a an id. For example, if you want to upload a picture from the camera:
<input type="file" accept="image/*" capture="camera" id="cameraInput">
Then in your js code, you will listen to change events on this element :
let storageRef = firebase.storage().ref('photos/myPictureName')
let fileUpload = document.getElementById("cameraInput")
fileUpload.addEventListener('change', function(evt) {
let firstFile = evt.target.files[0] // upload the first file only
let uploadTask = storageRef.put(firstFile)
})
Of course you need to have somehow included the firebase js library before.
And if you write in an older version of js, you also need to replace the let with var and add ; at the end of your lines.

How to display an image that hasn't been uploaded yet?

at first I need to apologize for my English, I'm not a good speaker.
But here's my problem:
I made an application, where you can edit questions for a game. These questions are on a server. You download a question and they are edited locally. At the end of the session you upload your question.
These questions should also contain images.
Therefore I made a little form, which saves the image to an image-heap as a FormData-Object.
This Form-Data Object is being saved into another Object.
Here's an example of how I do this:
var formDataTemp = new FormData();
var qcid = // given Id
if($('#editImageFileInput')[0].files[0] != undefined) {
formDataTemp.append("img", $('#editImageFileInput')[0].files[0]);
questionImageCache.push({
qcid: qcid, img: formDataTemp
});
}
There is more Data in the object, but i removed it to keep it simple.
There is also a list of all the questions the user has already downloaded. There he can switch from one question to another.
Now I want to display this image when the particular question comes up again. How can I do this without uploading it? Is there a way to display the image out of the javascript-object?
I don't know exactly how your code works, but this is how you can display an image before it is uploaded, using FileReader.
Javascript:
function loadImg(input) {
if (!input.files || !input.files.length) return null;
var fReader = new FileReader();
var img = $('#placeholder');
fReader.onload = function(e) {
$(img).attr('src', e.target.result);
};
fReader.readAsDataURL(input.files[0]);
}
HTML:
<input type='file' onchange="loadImg(this);" />
<img id="placeholder" src="#" alt="your image" />
JSFiddle example.
You can take the concept from this snippet and apply it to your own project :)

How to display selected image without sending data to server?

I am trying to show the client an image which he has selected:
<input type="file" onchange="showImage(this)"/>
But I can't read the value of the input, as I checked out here. Is it possible to display the image?
In onchange I can send the form to server and server can send the data back, but is it really necessary? Can't the client display the data without the ping-pong to the server? Is it a security issue?
You can use FileReader web-api object for this, see this snippet:
the HTML
<input id="src" type="file"/> <!-- input you want to read from (src) -->
<img id="target"/> <!-- image you want to display it (target) -->
the javascript
function showImage(src,target) {
var fr=new FileReader();
// when image is loaded, set the src of the image where you want to display it
fr.onload = function(e) { target.src = this.result; };
src.addEventListener("change",function() {
// fill fr with image data
fr.readAsDataURL(src.files[0]);
});
}
var src = document.getElementById("src");
var target = document.getElementById("target");
showImage(src,target);

select an image and manipulate it in javascript (no form submission)

Is there by any chance a way of letting the user select an image from his hard drive and without submitting it to the server use this image in the browser?
I need this because I want the users to be able to crop an image before sending this cropped image to the server (thus saving a post and some bytes of data).
What I tried to do is using an input type file and then capturing the submit event, but the value from the input is just a fake path (useless).
Any help would be greatly appreciated.
Here is a very basic example (with many globals, without input validation...) of image scaling: http://jsfiddle.net/89HPM/3/ . It's using the File API and a canvas element.
As #anu said the save can be done using toDataUrl method of the canvas.
In similar way you can achieve crop.
JavaScript
(function init() {
document.getElementById('picture').addEventListener('change', handleFileSelect, false);
document.getElementById('width').addEventListener('change', function () {
document.getElementById('canvas').width = this.value;
renderImage();
}, false);
document.getElementById('height').addEventListener('change', function () {
document.getElementById('canvas').height = this.value;
renderImage();
}, false);
}());
var currentImage;
function handleFileSelect(evt) {
var file = evt.target.files[0];
if (!file.type.match('image.*')) {
alert('Unknown format');
}
var reader = new FileReader();
reader.onload = (function(theFile) {
return function(e) {
currentImage = e.target.result;
renderImage();
};
})(file);
reader.readAsDataURL(file);
}
function renderImage() {
var data = currentImage,
img = document.createElement('img');
img.src = data;
img.onload = function () {
var can = document.getElementById('canvas'),
ctx = can.getContext('2d');
ctx.drawImage(this, 0, 0, can.width, can.height);
};
}​
HTML
<input type="file" name="picture" id="picture" /><br />
<input type="text" id="width" value="200" />
<input type="text" id="height" value="200" /><br />
<canvas width="200" height="200" style="border: 1px solid black;" id="canvas"></canvas>​
Here is a blog post which I made about that basic example: blog.mgechev.com
New HTML5 File API is probably the closest solution to what your looking for:
http://www.html5rocks.com/en/tutorials/file/dndfiles/
It allows you to browse for and read files within Javascript. Do whatever processing you like, and then upload to the server. Anything besides this is going to be very tricky indeed, and probably an unavoidable trip to the server and back.
Downside here is browser support.....as always
I am not sure which browsers work perfectly but HTML5 got DnD and File API. Let me give you steps which can work for you using FileAPI.
DnD API: Starts with the drop event when the user releases the mouse and the mouse-up event occurs.
DnD API: Get the DataTransfer object from the drop event
File API: Call DataTransfer.files to get a FileList, representing the list of files that were dropped.
File API: Iterate over all the individual File instances and use a FileReader object to read their content.
File API: Using the FileReader.readAsDataURL(file) call, every time a file is completely read, a new “data URL” (RFC 2397) formatted object is created and an event wrapping it is fired to the onload handler on the FileReader object.
FYI: The “data URL” object is Base64-encoded binary data, with a spec-defined header sequence of chars. Browsers understand them.
HTML5 DOM: set the image href to the File Data URL
You can't, for the following reasons:
For the reasons stated in this post: Full path from file input using jQuery
The fact that if you even try to create an img element loading a
local file path you'll get the error Not allowed to load local
resource: in your browser's console.
The fact that once you have an image in place you can only alter it's
appearance on screen and not alter the file on the system or send the altered image up to the server
You've stated that you need cross browser support, so HTML5 File API and Canvas API are out, even though they would only allow part of the functionality anyway.
I've just solved a problem closed to yours.
As everybody said you can't got the real image file address. But, you can create a temporary path and show the image in your page without submiting it to server. I'll show how easy it is, next to next paragraph.
Once you show it you can use some javascripts events to "pseudo-crop-it" and get the crop params (corners). Finaly you can add the params to some hidden field and submit the form. As a result you may use som php to crop the submited image at server and to save the result using a number of image formats as .png, jpg, gif, etc. Sorry if i do not write a complete solution, have not enough time.
/* some scripting to bind a change event and to send the selected image
to img element */
$(document.ready(function(){
$("input:file").each(function(){
var id = '' + $(this).attr('id');
var idselector = '#'+id, imgselector=idselector+'-vwr';
$(idselector).bind("change", function( event ){
(imgselector).fadeIn("fast").attr('src',
URL.createObjectURL(event.target.files[0]));
});
});
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.9.0/jquery.min.js"></script>
<!-- create a img element to show the selected image and an input file element to select the image.
ID attribute is the key to have an easy and short scripting
note they are related suffix -vwr makes the difference
-->
<img src="" id="image-input-vwr" alt="image to be cropped">
<input type="file" id="image-input" name="image_input">
Hope it help some body as it is a very old question.
Luis G. Quevedo

View image selected from file-system on client-side before upload?

I have an input tag on a form for selecting images to upload.
<div id="lowresDemo">
<img src="some-url" />
</div>
<input type="file" id="FileToUpload" name="FileToUpload" />
I've attempted to change the a thumbnail displayed on the form next to the input to affirm to the user that their selection was the intended with the following jquery code:
$('#FileToUpload').change(function () {
$('#lowresDemo img').attr('src', $(this).val());
});
...this doesn't work in any browser, for browser security reasons I beleieve (as I remember from the last time I did something like this years ago).
QUESTION:
Is there a way to present the user's choice of image before they submit the form -- and not just the filepath+name of the value in the input field, but a thumbnail showing the file they've selected?
Or does modern browser security prevent this?
It's possible with the File API (IE does not support the File API)
<input type="file">
<script type="text/javascript">
$(document).ready(function() {
$("input").change(function(e) {
for (var i = 0; i < e.originalEvent.srcElement.files.length; i++) {
var file = e.originalEvent.srcElement.files[i];
var img = document.createElement("img");
var reader = new FileReader();
reader.onloadend = function() {
img.src = reader.result;
}
reader.readAsDataURL(file);
$("input").after(img);
}
});
});
</script>
Working example: http://jsfiddle.net/ugPDx/
There is no way to perform the operation before uploading the picture.
But think of it in a different way - the user "doesn' care" if the picture is already uploaded - you could show the thumbnail after they've uploaded, and show a confirm checkbox. Gmail does this with their email attachments - as soon as you selected the file to attach, the upload starts. But the user always has the option to uncheck the file, and it won't be included in the email.

Categories

Resources