FileUpload control event - asp.net

I want to know how to raise an event for fileupload control....
In my project, as soon as I select a file(Image) it should show FILENAME,EXTENSION & SIZE in the labels given below.
Pls reply me....
Thanks in advance.

Until HTML5 becomes mainstream, it is completely impossible to do this without uploading the entire file to the server. (Except maybe with Flash)

Unfortunately this is not possible you need first to upload the file and then get it's information and add them to labels, otherwise you need to use third party plug-in to able you to do that such as flash or java applets.

You can use this code to get file information as soon as you select the file.
int filesize = FileUpload1.PostedFile.ContentLength;
string fileextension = FileUpload1.PostedFile.ContentType
string filename = Path.GetFileName(FileUpload1.FileName);

Related

Post a file from codebehind

I want to upload a file from codebehind.
I would like to explain my situation a bit.
My existing code is..
I have a fileupload control.
<asp:FileUpload ID="fuSRForm" runat="server" class="file"/>
Then from the codebehind, I check the conditions for that control.
if (fuSRForm.HasFile && (fuSRForm.PostedFile.ContentType.ToString().Trim().ToLower().Contains("pdf") || fuSRForm.PostedFile.ContentType.ToString().Trim().ToLower().Contains("application/vnd.openxmlformats-officedocument.wordprocessingml.document") || fuSRForm.PostedFile.ContentType.ToString().Trim().ToLower().Contains("msword")))
And if the conditions are met,
I used the Sitecore API to upload the file.
This is the part of uploading API.
// creating necessary arguments to be passed to the processor
UploadArgs args = new UploadArgs();
// adding http files collection
args.Files = base.Request.Files;
So, the API is grabbing all posted files by using base.Request.Files
My new situation is that I creat a pdf file when the user click Submit.
Then I save it in a folder named asyncupload
After that I have to upload it to Sitecore using the same API
So, I tried to change the base.Request.Files to my file.
But I am unable to change that.
So, I will have to upload my file using FileUpload control.
FileUpload tempFU = new FileUpload();
tempFU.PostedFile= ????
args.Files = base.Request.Files;
I am stuck right here. I can either post my file from code behind or change the base.Request.Files to my file.
either way, I am stuck. Anyone can solve that?
I'm not sure what your end goal here is. Maybe you could post some more code if I've understood you incorrectly. But here's how to add a file to the Media Library: Brian Pedersen: Adding a file to the Sitecore Media Library programatically
If you are using an <asp:FileUpload /> control, then you can save the file to server disk like this:
string filePath = Path.Combine(Server.MapPath("~/"), "upload/tempfile.tmp");
FileUpload1.SaveAs(filePath);
Then call the AddFile method from the link I provided above:
AddFile(filePath);
You need to use handler in the api you are going to hit and hit it by
using (WebClient client = new WebClient())
{
client.UploadFile(Sitecore Handler, FilePath);
}

stupid caching in asp.net

i use such code
string.Format("<img src='{0}'><br>", u.Avatar);
u.Avatar-it's like '/img/path/pic.jpg'
but in this site i can upload new image instead old pic.jpg. so picture new, but name is old. and browser show OLD picture (cache). if i put random number like /img/path/pic.jpg?123 then works fine, but i need it only ufter upload, not always. how can i solve this?
string imgUrl = _
string.Format("<img src='{0}?{1}'><br>", _
u.Avatar, _
FunctionThatLookupFileSystemForItsLastModified(u.Avatar).Ticks.ToString());
Instead of linking to the images directly, consider setting up a generic HTTP handler to serve the images.
MSDN: HTTP Handlers and HTTP Modules Overview
Stack Overflow: How to use output caching on .ashx handler
Append DateTime.Now.Ticks to the image url:
string imgUrl =
string.Format("<img src='{0}?{1}'><br>", u.Avatar,DateTime.Now.Ticks);
EDIT: I don' think this best practice are even a practice I would use. This is just a suggestion given the limited information given in case the Random implementation isn't truly Random.
Read your post again,,, sorry for general answer.
To workaround it do following
On Application_Start create a Dictionary with uploaded images save it on Application object, set it to null. Once you upload an image add it to this Dictionary. Wrap every place avatars appear on your website with function that evaluates image in Dictionary if found return imagename.jpg?randomnumber and then delete it from a Dictionary else return just an imagename.jpg.
This is going to be heavy because you will need to check each image in Dictionary but this will do exactly what you need.
You can set cache dependancy using the System.Web.Caching.CacheDependency namespace.
This can set the dependancy on the file uploaded, and will release the cache for that file automatically when the file changes.
There are lots of articles and stuff on MSDN and other places so I will not go into details on all that level of detail.
You can do inserts, deletes and other management of cache using the tools available.
(and this does not require you to change the file names or tack on stuff - it knows by the file system that the file changed)

Is it possible to create a .ascx virtually? i.e. not on disk, but as a string?

I was wondering if it was possible to load a asp.net control (.ascx) that doesn't reside on the file system?
Like say a string variable?
Not a string varible but you can load it from resources or zip file, but you have to have full trust. Google for VirtualPathProvider.
As of 4.0 you don't have to have full trust.
System.Reflection.Emit
Assembly.Load(byte[])
No designer for you if you do this though.
You could try this:
string controlString = //read or build it
Control control = this.Page.TemplateControl.ParseControl(controlString);
More information is available here:
http://msdn.microsoft.com/en-us/library/kz3ffe28.aspx

Opening an image in vb to send into a database - Asp.Net

I'm currently patching an asp.net program where I need to be able to send an image to an SQL Server 2005 DB. It works fine when I use the asp:fileupload control, but the trick is that when the user deletes the image, I'm supposed to replace it with an image from the server saying "empty", in code-behind.
I know how to open, use and save text files in vb, but I can't find any information anywhere on how to open an image / binary file in a similar manner so that I can use it as an sql-parameter on the update query.
Below is an example of how easy it is to use a file from the fileupload control.
Dim t_id As Integer = Convert.ToInt32(Request.QueryString("id"))
open()
Dim picture As New SqlParameter("#picture", pictureFileUpload.FileBytes)
Dim id As New SqlParameter("#id", t_id)
myCommand = New SqlCommand("spChangeImage")
myCommand.CommandType = CommandType.StoredProcedure
myCommand.Connection = conn
myCommand.Parameters.Add(picture)
myCommand.Parameters.Add(id)
myCommand.ExecuteNonQuery()
close()
Now I need a way to open an image file and set it as a parameter in a similar manner, but I've no clue as to how to go about doing that. All the search results are focused on opening and viewing an image in html, I just need the binary to use it in the query. I'm trying to use binaryreader but even then I've no idea how to actually map the file to begin with.
Thanks in advance for any help!
Personally, I wouldn't store this image in the database when the user deletes their value. I would set the column to null. When writing the image I would detect if the column is null, then read the file and write it to the response. If you do this, then you won't need to accumulate anything into a local buffer, you can just write each buffer to the response as it is read. You can use FileInfo.Length to determine the content length of the response.
If you insist on putting the image in the DB, you can also use FileInfo.Length to determine the size of buffer you need to hold the image. Use your BinaryReader to read this length of bytes into the buffer. The buffer then becomes your parameter to the SQL command.
this might help.

What's the best way to display an image from a sql server database in asp.net?

I have a sql server database that returns byte for the image. If I use the tableadapter wizard and set it to my stored procedure and preview data, it pulls back an image. It automatically turns it into an image in the preview data. I don't see it as a string of Ints or anything.
How can I display it on my asp.net webpage with a gridview and objectdatasource?
I have searched and foudn where the imagefield can point to a url on another page that does the byte transformation but I'm not sure it's the best. I found another way that creates a temp file.
Just trying to see the best way to do it.
edit - I am trying not to use a temp file. If I cannot use a gridview a regular image field is ok.
asp.net 2.0, c#.
Thank you for any help.
edit
ended up with:
protected void Page_Load(object sender, EventArgs e)
{
string id = Request["id"];
string connstr = "DSN=myserver";
OdbcConnection conn = new OdbcConnection(connstr);
OdbcCommand cmd = new OdbcCommand("{call mySP (?)}", conn);
cmd.CommandType = CommandType.StoredProcedure;
// Add the input parameter and set its properties.
OdbcParameter parameter = new OdbcParameter();
parameter.ParameterName = "#MyParam";
parameter.OdbcType = OdbcType.VarChar;
parameter.Direction = ParameterDirection.Input;
parameter.Value = id;
// Add the parameter to the Parameters collection.
cmd.Parameters.Add(parameter);
conn.Open();
OdbcDataReader dr = cmd.ExecuteReader();
while (dr.Read())
{
byte[] buffer = (byte[])dr[0];
Response.ContentType = "image/jpg";
Response.BinaryWrite(buffer);
Response.Flush();
}
}
and this on the calling page:
<asp:Image ID="Image1" ImageAlign="Middle" ImageUrl="show.aspx?id=123" Runat="server" />
Two options:
Create a temp file - The problem with this approach is that you have to create the file, which means your web must have write access to a directory which is not a great thing. You also need to have a way to clean up the images.
Serve it from another URL - This is my preferred method, as you have no disk access required. A simple http handler (ashx) is a great method to serve up the image.
Edit
If you need session state in the ashx, check out: Asp.net System.Web.HttpContext.Current.Session null in global.asax.
Edit
Couple more thoughts. There are some cases where using a temp file might be better. For example if your images are requested frequently by a lot of users. Then storing the images on the disk would make sense, since you could write the file once, this does increase the maintance complexity but depending on traffic it might be worth it since this would let you avoid calling back into the .net stack and leverage IIS caching of static content.
I wrote the SqlReader plugin for open-source ImageResizing.Net library to allow you to serve and display images from a SQL database in the most performance-optimal way.
Even if you don't need to do any image processing whatsoever, it's still (a) the easiest, and (b) the most efficient way to do it. You can combine it with disk caching (which provides automatic cleanup) to get the best performance that is possible.
Installation is easy - 2 nuget commands, or copy & paste into Web.Config, your pick.
If you need help, support is free and fast.
The sample code you added is good but you should move it to a .ashx file which is meant for such things.
Here is some example code on how to do this.

Resources