C# Get and Set property programmatically on FileUpload1.PostedFile - c#

I have a file upload control on my asp.net mobile application.
My requirement is while accessing a local folder path from browser; I need to set the path programmatically.
And don’t allow user to brows the file.
My question is, when I try to access File-upload Control property name like -> Posted-file
That will not allow me to set the values programmatic. That will allow read-only currently.
It is possible to set the values programmatically on file-upload control?
Or Is there another way to expose the FileUpload1.PostedFile property using like web User Control?
Exp:
public partial class TestWebUserControl : System.Web.UI.UserControl
{
public System.Web.HttpPostedFile PostedFileText
{
get { return FileUpload1.PostedFile; }
//set { FileUpload1.PostedFile = value; }
}
}

you cannot set value directly to the file post
There is no direct solutions as mentioned to set value of file upload control after postback in asp.net. Even if you tried to set the value of FileUpload control through javascrip, that will not work because of security restrictions.
You can't also set the FileUpload value on the server because the FileName and other attributes is readonly.
solution:
You can use:
label control to display the last selected file .
hiddenField Control to transfer the selected file from the client to server.
but you need also to remeber the last posted file because in case you don't select a file from FileUpload control and then posted back, you will notice that the FileUpload.postedFile value will be gone , so you have to save the posted file somewhere.
See this for an example;
ASPX Code
<form id="form1" runat="server">
<asp:FileUpload ID="FileUpload1" runat="server" /> <br />
<asp:Label ID="lblCurrentFile" runat="server"></asp:Label><br />
<br />
<asp:Button ID="BtnSubmit" runat="server" Text="postBack" />
<br />
<asp:HiddenField ID="HiddenField1" runat="server" />
</form>
find full solution |: http://www.nullskull.com/q/10140208/we-cant-set-value-of-file-upload-control-after-postback-in-aspnet.aspx

Why do you want to modify the Request? You cant change it.
If you want you read it and assign it in a local variable(byte[]).
byte[] buffer = new byte[FileUpload1.PostedFile.InputStream.Length];
FileUpload1.PostedFile.InputStream
.Read(buffer, 0, FileUpload1.PostedFile.InputStream.Length);

Related

Upload FileUpload

I'm working on a project in which I have to upload .txt files. I'm using asp.net FileUpload. Here is a piece of code:
<div class="custom-file">
<asp:FileUpload ID="inputFileTXT" CssClass="custom-file-input" runat="server" />
<label id="lblFileName" runat="server" class="custom-file-label" for="inputFileTXT">Elegir archivo</label>
</div>``
I'm using styles from MDBootstrap.
The thing is that I want to do stuff when a user clicks on the asp:fileUpload element and selects a file WITHOUT CLICKING ON A BUTTON. I've been searching but I didn't find how to detect dynamically this action. The asp:fileUpload has no event such as OnUploading.
PD: I tried using an UpdatePanel but when it makes the postback it seems like the uploaded file disapears. Maybe this is the way but I couldn't make it work.
You can add a dummy LinkButton to the page and leave it empty, but give it an OnClick, in which you would process the file.
<asp:FileUpload ID="FileUpload1" runat="server" accept="image/*" />
<asp:LinkButton ID="LinkButton1" runat="server" OnClick="LinkButton1_Click"></asp:LinkButton>
Then in code behind add the onchange trigger to the FileUpload control that will do a PostBack of LinkButton1.
protected void Page_Load(object sender, EventArgs e)
{
FileUpload1.Attributes.Add("onchange", "__doPostBack('" + LinkButton1.UniqueID + "','')");
}
PS do not put a FileUpload Control in an UpdatePanel.
You want to detect when a file is assigned to the upload just use change event.
Jquery solution:
$('#inputFileTXT').on('change', function(){
//do stuff
});
javascript solution:
<asp:FileUpload ID="inputFileTXT" CssClass="custom-file-input" runat="server" onchange="doStuff(this);" />
function doStuff(control){
//do stuff
}
You can then read files by using FileReader api (https://developer.mozilla.org/en-US/docs/Web/API/FileReader).
and access files using .files:
var files = $('#inputFileTxt').files;
Please have a look at this link
You should get the file details in FileUpload1 (fileUpload control Id: inputFileTXT in your case).

FileUpload.HasFile returns "False" for multiple files upload - ASP.net

I am using ASP.net FileUpload control to upload multiple files in database.
<asp:UpdatePanel ID="UP_div_askQ" UpdateMode="Conditional" runat="server">
<ContentTemplate>
<asp:FileUpload ID="FUQuestionFiles" CssClass="form-control" AllowMultiple="true" runat="server" />
<asp:Button ID="btnQSave" runat="server" CssClass="btn btn-success" Text="ASK QUESTION" OnClick="askQuestion" />
</ContentTemplate>
<Triggers>
<asp:PostBackTrigger ControlID="btnQSave" />
</Triggers>
</asp:UpdatePanel>
In code behind I am using HasFile to check if files are present or not.
log.Debug("there are file" + FUQuestionFiles.HasFile.ToString());
But HasFile returns false when more than one file is selected.
Note: In case where only one file is selected, it returns true.
Thanks for your help.
FileUpload has two different properties for checking if a/any file has uploaded:
FileUpload.HasFile:
Gets a value indicating whether the FileUpload control contains a
file.
FileUpload.HasFiles:
Gets a value that indicates whether any files have been uploaded.
The best way to check if any files is uploaded is to check both HasFile and HasFiles together.
if(fileUpload1.HasFile || fileUpload1.HasFiles)
// do some code!
Edit 1:
Have you tried to add line below in the Page_Load?
Page.Form.Attributes.Add("enctype", "multipart/form-data");
Edit 2:
Can you please explain what difference this line of code made?
From this Forms in HTML documents draft in W3C:
The content type "application/x-www-form-urlencoded" is inefficient
for sending large quantities of binary data or text containing
non-ASCII characters. The content type "multipart/form-data" should be
used for submitting forms that contain files, non-ASCII data, and
binary data.
If the form contains a file input the enctype attribute of the form should set to multipart/form-data.
I think you faced that problem because you put the FileUpload inside the UpdatePanel.

how to upload an image file without any postback in ASP.NET

I am uploading a file using the <asp:FileUpload> and <asp:button> controls but I want to do it without a postback. On button click I execute the following code.
protected void btnUpload_Click(object sender, EventArgs e)
{
string strFileName = Path.GetFileName(FileUpload1.FileName); //fileupload1 is the <asp:fileupload ID
FileUpload1.SaveAs(Server.MapPath("~/UploadFile/" + strFileName + ""));
imgUpload.ImageUrl = "../UploadFile/" + strFileName + ""; //imgupload is the <img ID on which I am showing the image after upload
imgUpload.Visible = true;
}
After uploading the file I am showing the saved image from the specified folder in my project solution, but on clicking the upload button the whole page gets loaded and I don't want the postback on clicking the upload button.
just add the script
<script language="javascript">
function Change(obj) {
__doPostBack("<%= btnUpload.ClientID %>", "");
}
</script>
Call the script in your button click event like this
<pre>
onchange="Change(this);"
</pre>
Your image control added in the update panel with contentTemplate
<asp:FileUpload ID="imgFileUploader" runat="server" />
<asp:Button ID="btnUpload" runat="server"
Text="Upload" onclick="btnUpload_Click" onchange="Change(this);" />
<br />
<br />
<asp:ScriptManager ID="ScriptManager1" runat="server">
</asp:ScriptManager>
<asp:UpdatePanel ID="UpdatePanel1" runat="server">
<ContentTemplate>
<img id="imgOrginal" runat="server" style="height: 200px; width: 200px;" />
</ContentTemplate>
</asp:UpdatePanel>
for more details
if you are using ASP.Net file uploader then is is not possible.. you can use Ajax file uploader for this purpose
Best way to upload images without any postback, you can try AsyncFileUpload control in Asp.net Ajax. A good example is here :-
http://www.aspsnippets.com/Articles/Using-ASP.Net-AJAX-Control-Toolkits-AsyncFileUpload-Control.aspx
Thankyou
I think you are asking about uploading files through partial request. Using ASP.NET file upload control it is not possible. Even it is wrapped inside update panel, it will not work. It needs to have synchronous trigger to make it work, that means it does full post back.
If you are using ASP.NET AJAX, checkout asyncfileload control and newly added 'Ajax file upload' control. These controls are present in Ajax control tool kit. Please go through the documentation since each have their limitations.
If they doesn't suit your needs, try for open source Ajax file upload controls like neat upload etc.
You can't do this using simple ASP.NET WebForms.
Do some research into what is known as the page lifecycle. Code behind methods like the one you've included are / can be executed only as part of a postback or server-side action.
If you want client-server interaction without a postback then you need to use javascript. You can use javascript alongside ASP.NET, and I believe there is a Microsoft implementation of 'AJAX' in the .NET framework.
You need to use ajax for this purpose. There are plenty of examples available on internet. Just google it.

How to restrict file type in FileUpload control

Is it possible to allow the fileupload control to show only images?
When we click the Browse button it should show only images.
In 2015, web browsers support the input accept attribute, so you can do this:
<asp:FileUpload ID="fileUploader" runat="server" accept=".png,.jpg,.jpeg,.gif" />
Keep in mind Visual Studio may show you a message about this as an invalid attribute of the FileUpload ASP tool, however.
I found no direct solution for this problem.
This is my workaround using the RegularExpressionValidator:
<asp:FileUpload ID="fuImportImage" runat="server" />
<asp:RegularExpressionValidator ID="regexValidator" runat="server"
ControlToValidate="fuImportImage"
ErrorMessage="Only JPEG images are allowed"
ValidationExpression="(.*\.([Jj][Pp][Gg])|.*\.([Jj][Pp][Ee][Gg])$)">
</asp:RegularExpressionValidator>
You cannot strictly restrict the file type, but if the browser supports it you can cause it to initially show just a certain type of file:
<form method="post" action="blahblah.blah">
<input type="file" name="image" id="image" accept="image/png, image/jpeg" />
</form>
No, in web you can't from client side, evidently from server side you can do amazing things.
For this kind of thing, programmers normally use Activex, flash or the like.
//VALIDATE FILE EXTENTION
var _validFileFlag;
function fValidFileExt(vfilePath){
var vFileName=vfilePath.split('\\').pop();
var vFileExt=vfileName.split('.').pop();
if(vFileExt.toUpperCase()=="JPEG" || vFileExt.toUpperCase()=="JPG"){
_validFileFlag = true;
}
_validFileFlag = false;
}
<asp:FileUpload ID="FileUpload1" onchange="fValidFileExt(this.value);" runat="server" />
Check '_validFileFlag' while saving data/upload..
Use accept attribute to show only images in file browser like below -
<asp:FileUpload ID="FileUploadFileType" runat="server" CssClass="form-control" accept=".png,.jpg,.jpeg,.gif" />
with asp.nets RegularExpressionValidator to validate selected file type with validation message.
<asp:RegularExpressionValidator ID="RegExValFileUploadFileType" runat="server"
ControlToValidate="FileUploadFileType"
ErrorMessage="Only .jpg,.png,.jpeg,.gif Files are allowed" Font-Bold="True"
Font-Size="Medium"
ValidationExpression="(.*?)\.(jpg|jpeg|png|gif|JPG|JPEG|PNG|GIF)$"></asp:RegularExpressionValidator>
Assuming you mean uploading images only.
You can check the ContentType property of the file (I.e. image/gif).
Take a look here for an example: https://web.archive.org/web/20100306030822/http://www.15seconds.com/issue/061116.htm
With plain <input type="file">, I am afraid it's not possible on the client-side.
However, some 3rd party uploader such as SWFUpload provides this functionality.

How to correctly use the ASP.NET FileUpload control

I'm trying to use the FileUpload control in ASP.NET
Here's my current namespace setup:
using System;
using System.IO;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Web.UI.WebControls.WebParts;
And within my class, I'm just using:
FileUpload fileUpload = new FileUpload();
However, none of the attributes that are normally part of FileUpload seem to be available... such as .HasFile. I'm attempting to make the Button click method in the code behind, I have noticed that most of the usage of .HasFile is in the code in front, however it was my understanding that this shouldn't matter.
Does anyone know why?
ASP.NET controls should rather be placed in aspx markup file. That is the preferred way of working with them. So add FileUpload control to your page. Make sure it has all required attributes including ID and runat:
<asp:FileUpload ID="FileUpload1" runat="server" />
Instance of FileUpload1 will be automatically created in auto-generated/updated *.designer.cs file which is a partial class for your page. You usually do not have to care about what's in it, just assume that any control on an aspx page is automatically instantiated.
Add a button that will do the post back:
<asp:Button ID="Button1" runat="server" Text="Button" onclick="Button1_Click" />
Then go to your *.aspx.cs file where you have your code and add button click handler. In C# it looks like this:
protected void Button1_Click(object sender, EventArgs e)
{
if (this.FileUpload1.HasFile)
{
this.FileUpload1.SaveAs("c:\\" + this.FileUpload1.FileName);
}
}
And that's it. All should work as expected.
Instead of instantiating the FileUpload in your code behind file, just declare it in your markup file (.aspx file):
<asp:FileUpload ID="fileUpload" runat="server" />
Then you will be able to access all of the properties of the control, such as HasFile.
Adding a FileUpload control from the code behind should work just fine, where the HasFile property should be available (for instance in your Click event).
If the properties don't appear to be available (either as a compiler error or via intellisense), you probably are referencing a different variable than you think you are.
My solution in code behind was:
System.Web.UI.WebControls.FileUpload fileUpload;
I don't know why, but when you are using FileUpload without System.Web.UI.WebControls it is referencing to YourProject.FileUpload not System.Web.UI.WebControls.FileUpload.
I have noticed that when intellisence doesn't work for an object there is usually an error somewhere in the class above line you are working on.
The other option is that you didn't instantiated the FileUpload object as an instance variable. make sure the code:
FileUpload fileUpload = new FileUpload();
is not inside a function in your code behind.
Old Question, but still, if it might help someone, here is complete sample
<form id="form1" runat="server">
<div>
<asp:FileUpload ID="FileUpload1" runat="server" /><br/>
<asp:Button ID="Button1" runat="server" Text="Upload File" OnClick="UploadFile" /><br/>
<asp:Label ID="Label1" runat="server" Text=""></asp:Label>
</div>
</form>
In your Code-behind, C# code to grab file and save it in Directory
protected void UploadFile(object sender, EventArgs e)
{
//folder path to save uploaded file
string folderPath = Server.MapPath("~/Upload/");
//Check whether Directory (Folder) exists, although we have created, if it si not created this code will check
if (!Directory.Exists(folderPath))
{
//If folder does not exists. Create it.
Directory.CreateDirectory(folderPath);
}
//save file in the specified folder and path
FileUpload1.SaveAs(folderPath + Path.GetFileName(FileUpload1.FileName));
//once file is uploaded show message to user in label control
Label1.Text = Path.GetFileName(FileUpload1.FileName) + " has been uploaded.";
}
Source: File Upload in ASP.NET (Web-Forms Upload control example)

Categories

Resources