Reputation: 247
With using an asp FileUpload control, is there anyway i can have an asp Image populated with the image as soon as i select one within the FileUpload control without uploading it to a folder etc, just populate the asp Image control with the image selected.
Upvotes: 2
Views: 555
Reputation: 3047
Here is a way to do it directly on the Client Side : JSFiddle
var input = document.getElementById('fileUp');
var img = document.getElementById('img1');
if (input.files && input.files[0]) {
var reader = new FileReader();
reader.onload = function (e) {
img.src = e.target.result;
}
reader.readAsDataURL(input.files[0]);
}
There are a few issues with this approach.
The Img's source will not be stored retained on Postback, you can create a workaround for this but it's a little indepth.
The use of this requires support for the HTML5 Web FileReader API. Which is only supported by a limited amount of browsers (See full support list at the bottom of the link I posted)
If you only require this for client-side processing and only for IE10 / Chrome / Other supported browsers then you'll be fine. Otherwise this approach will not work for you.
Upvotes: 1
Reputation: 1206
You can't do it directly but here is a neat way to do it without saving in your proper destination folder.
Taken from http://forums.asp.net/p/962719/1197308.aspx
for security reasons the FileUpload control doesn't allow you to pre-load the file. However you can have a temporary directory(e.g. preloaddirectory) for files before placing it in the production directroy (e.g. uploadedDirectory). After you saved your file to that temp directory, you can use FileUploadControl.PostedFile.InputStream to get the content of the posted file into a byte array. From there you can do:
C#:
byte[] buff ; buff = (byte[])FileUploadControl.PostedFile.InputSream; Response.ContentType = FileUploadControl.PostedFile.ContentType; Response.BinaryWrite (buff);
VB.NET dim buff as byte()
buff = Ctype(FileUploadControl.PostedFile.InputStream, byte()) Response.ContentType = FileUploadControl.PostedFile.ContentType Response.BinaryWrite (buff) ...
this will return the image as a stream of bytes w/c will be interpreted by the browser(assuming you have the correct content type) to be your image and will display accordingly
Upvotes: 0