File Upload/Download in ASP.NET - c#

Ok, I'm a real newbie at the ASP stuff... I have two related questions:
What are my options for controls I can dynamically add to my webpart to allow a user to upload large files >100MB to the server?
What are my options for controls to trigger a download of a large file in a web browser with a "Save As" dialog box, so that the server can generate a file and send it to the user?
I've seen examples for FileUpload controls, HttpRequest/HttpResponse controls, FileWebRequest controls... its never clear if the examples are intended for windows apps scraping off websites, or client scripts that are tied to buttons, or serverside code that acts on a postback. I guess I'm looking for the latter... something I could write in the server code to trigger the interaction.
If anyone knows where I can find a clear tutorial, that would also be appriciated.

By default, ASP.Net restricts the file uploaded to the server to be 4 MB. We can increase this setting in Web.Config through the tag.
The below configuration setting is configured for all default values.
<httpRuntime
executionTimeout="110"
maxRequestLength="4096"
requestLengthDiskThreshold="80"
useFullyQualifiedRedirectUrl="false"
minFreeThreads="8"
minLocalRequestFreeThreads="4"
appRequestQueueLimit="5000"
enableKernelOutputCache="true"
enableVersionHeader="true"
requireRootedSaveAsPath="true"
enable="true"
shutdownTimeout="90"
delayNotificationTimeout="5"
waitChangeNotification="0"
maxWaitChangeNotification="0"
enableHeaderChecking="true"
sendCacheControlHeader="true"
apartmentThreading="false" />
To increase the default upload size, we need to increase the value of maxRequestLength property to whatever we want in KB. Default is 4096 KB(4MB).
To upload 100 MB, set
maxRequestLength="102400"
Copy the above configuration inside tag in Web.Config.
this is the link http://programming.top54u.com/post/ASP-Net-FileUpload-Size-Limit-Example.aspx

ASP.NET does have a FileUpload control. For files of that size however, I recommend that you look at an alternative solution, like FTP.

Related

Check if user has logged in or not

I have a gridview in which one column contains images. I have used lightbox to zoom the clicked image. But when I right click on the image and select an option "Open link in new tab" then the image gets opened in a new tab. that's not a problem.
After that I press log out button. Now I copy that image link and I paste it on the address bar, the same picture get's opened. I want that first it should be checked whether the user has logged in or not and then open the image if he has logged in otherwise not.
All the images of the gridview are stored in a folder named "product images".
I am already checking login status on the page where gridview is used.
Tell me what to do.
Your problem is that security trimming is not applied on your images.
Static resources do not follow the same route as an asp.net page so security trimming is not applied on images.
As long as you have a web.config file that do not allow unauthorized users in that images folder, you could handle the problem by setting at web.config => system.webServer => modules
<modules runAllManagedModulesForAllRequests="true">
... but this would mean that all resources would be routed through the asp.net pipeline which would could generate performance issues.
In response to you question (my solution):
I would actually go through another way, which would be a little more difficult, which would be:
Make the folder product images invisible to any user by using iis Request Filtering (=>Hidden Segments=> Disallow access to that folder)
Then create a custom http handled (.ashx file) in which I would have the image name as a parameter. That handler at ProcessRequest would get the image parameter, open the specific file and stream the data from the image to response.)
That handled could be easy under security trimming, as long as it goes through ASP.NET pipeline so users not logged in would not have access to the handler. Performance would be some slower but only for those specific images. Also note that you should change any direct calls to the images. For example, if you had src='/product images/imageA.png', this should change as src='/ImagesHandler.ashx?image=imageA.png'.
After your comment on difficulty and Abhishek Punj answer I would like to mention:
My solution wouldn't need to register handlers for each file type (what if you add a .jpg file type afterward and haven't registered it?).
Also, even with Abhishek Punj answer you would still need to stream
image data from the image file to response.
In addition, with my solution, you won't need to custom check for
user permissions at ProcessRequest but ASP.NET security trimming
would handle it.
Also, my solutions tries to "protect the folder"
where Abhishek Punj tries to "protect the file type globally".
But most important, Abhishek Punj answer means that ALL IMAGES would go through the ASP.NET pipeline which means that if you had any
images at log on form for example, they wont be shown to the user
too! After all, if you would hanlde all image file types, then why wouldn't you go with runAllManagedModulesForAllRequests="true", without any coding ?
You can create a new handler and register it in IIS for the type of extension that your image file has. In that handler on begin request you can check if the user is authenticated in using the Principle set by the forms authentication. This would not fire for all the static files and hence would perform better than the solution mentioned by George.
However there is one more problem that you will face.. all the static resources are cached by the browser and hence it might not send in a request to the server at all and just display the image to the user without authentication.
To deal with this problem you will need to set the no-cache header in the response from the custom handler you wrote in the first step so that the browser dosent cache the response and always hits the server to serve the response.
Response.AppendHeader("Cache-Control", "no-cache, no-store, must-revalidate"); // HTTP 1.1.
Response.AppendHeader("Pragma", "no-cache"); // HTTP 1.0.
Response.AppendHeader("Expires", "0"); // Proxies.
Hope this gives you the desired direction.
EDIT: Based on points raised by George
runAllManagedModulesForAllRequests="true" will not only be triggered for all images it will also be triggerd for all CSS files, and javascript files as well.. hence increasing the overhead.
If you want to specifically restrict files just in a specific directory a very simple way would be to mention the directory as a key in the config and do a regex comparison to check if the request is required to be authenticated or not.. this can also be extended to cater to various files or directories to be included or restricted with a custom configuration section as per need.
As far as registering the handler for requests with other file extensions is considered its a matter of seconds.. not a painful task.

uploading a file from folder with out browse in asp.net

i just wanna upload afile from a fixed path, so i dont want browse button, I need just a TextBox(Path of my file some thing like c:/junk/upload) and and upload button.some thing like
[TextBox.Path][UploadButton]
or can i get the code in java applets or any other lanaguage?
For security reasons, a webpage loaded in a browser from internet cannot directly refer the local file system. You need a desktop application or plugin to achieve this.
no we can make using asp.net or java applets and yes what you said is right, security reasons! , but every applications has a sand box limits and thats include file handling as default , and we achived that. with out problem

Not showing the images in live server which is showing in my local host

I am working on the Mailbox Module in VS2010 with C#
I have made a control with ascx page and in that page I have created Three different gridviews for Inbox,SentItems and Deleted Items.
In all the three gridviews I have added two columns for the Images for Reply and Forward messages which is shown where the user reply or forward the message.
The functionality works perfectly in my localhost.
But today i have deployed it on live server.
Where I found that I does not showing the images.
When I inspected elements through firebug I found in the HTML source code that it shows me that the "Failed To Load The Given URL" while for other images it shows the images.
Can Anyone tell me why is it happening and help me..?
Check if the url is pointing to the correct physical path on live sever.
Refer this - ASP.NET Web Project Paths
ASP.NET resolves the ~ operator to the root of the current application. You can use the ~ operator in conjunction with folders to specify a path that is based on the current root.
The following example shows the ~ operator used to specify a root-relative path for an image when using the Image server control In this example, the image file is read from the Images folder that is located directly under the root of the Web application, regardless of where in the Web site the page is located.
<asp:image runat="server" id="Image1"
ImageUrl="~/Images/SampleImage.jpg" />
You can use the ~ operator in any path-related property in server controls. The ~ operator is recognized only for server controls and in server code. You cannot use the ~ operator for client elements.
I found solution of this error.
Basically in Help desk set permision red and write where u hosting website. then solve thi solution.
2nd thing: u check folder image folder path where u save image in Help desk

AjaxControlToolkit's AsyncFileUpload misbehaving when deployed online

In case it matters, the following is inside a toolkit popup, which has an update panel in it.
<p>
<asp:Label Text="Picture" runat="server" Width="75"></asp:Label>
<ajaxToolkit:AsyncFileUpload ID="MediaPicture" runat="server" Width="200"
OnClientUploadStarted="BlockSubmits" ClientIDMode="AutoID"
OnClientUploadError="UnblockSubmits" PersistFile="true"
OnClientUploadComplete="UnblockSubmits"
/>
</p>
The javascript functions just block / release a submit button, to prevent problems during uploads.
This works fine on localhost, but when deployed online on a GoDaddy server, I can't seem to upload files over a few KB, even when locally I could upload bigger files (~2MB)...
I can't seem to find the reason for this behavior, could it be on the IIS? I read something about the app pool clearing before the upload could complete, could this be happening?
Btw, just in case, server-side I just take the picture out of this control
byte[] picture = MediaPicture.FileBytes ?? (string.IsNullOrEmpty(mediaID) ? null : Media.SelectByID(int.Parse(mediaID)).GetPicture());
There's some extra logic in there about whether I'm in edit mode or not, and if the current record has a picture, I'll take that over no picture,
And then I store it on the database.
any thoughts as to why this might be happening?
thanks!
If I understand your situation correctly, the problem is caused by the AsyncFileUpload being located inside the updatepanel, thereby having the file upload happen during a postback...
This blog post has a decent explanation of why.
As for why it works locally, if it is the problem as explained above, it's because of the way the browser handles "local" from "internet" domains.
The Assync upload of the ajax toolkit still has to have a post with the maximum request size of ASP.NET.
This max size is setted in the web.config of your application AND inside IIS. Since you are using a third party provider... try to fiddle with the web.config in the section
<httpRuntime maxRequestLength="40960"/>
If this won't help you out, check out the SWFUpload control... saved my skin a couple of times.
Regards,
I guess you use different IIS versions in your development environment and in the the production server (in this case Go Daddy).Can you verify and let me know the exact IIS versions so that I can provide you a better solution? Cause IIS 7.0 has a slightly different configuration than IIS 6.0.
I was experiencing the exact same problem, but including the website in the "Local Intranet" zone in IE the security setting was a workaround.
However, I updated the Ajax Control Toolkit and the problem was completely solved. There is no more need to mess with the security setting.

fileupload path is missing

hai friends
I am using a file upload control to upload the files if the user browse and upload the file. after uploading the path gets disappears. i should be maintain there itself. how?
Well, this is the default behavior of the browsers for security reasons
have a look at MS support site for IE http://support.microsoft.com/kb/266087
Edit
In your code behind you can try something like
fileUpload.Attributes.Add('value',filename);
see if this works.

Categories

Resources