I have been playing around with asp.net webforms controls to learn how to use them better and I seem to have gotten myself in some trouble with the fileupload control. I noticed that when I upload img's the code I wrote works but when I try to upload a PDF or a RAR file I get an error saying that
the connection to localhost has been interupted
This is my code:
<div id="center">
<asp:FileUpload ID="FileUpload1" runat="server" />
<br />
<asp:Button ID="Button1" runat="server" onclick="Button1_Click" Text="Button" />
<asp:Label ID="Label1" runat="server" Text="Label"></asp:Label>
</div>
protected void Button1_Click(object sender, EventArgs e)
{
if (FileUpload1.HasFile) {
try
{
string filename = FileUpload1.FileName;
FileUpload1.SaveAs(Server.MapPath("~/Files/") + filename);
Label1.Text = "File has been uploaded";
}
catch (Exception ex) {
Label1.Text = "The file could not be uploaded";
}
}
}
What is the problem? Why can't I upload other file types?
When you try uploading files that is more than the default max size (ie. 4MB) then you may end up in page reset or interruption. You can set the max size in config file.
<system.web>
<httpRuntime executionTimeout="240" maxRequestLength="20480" />
</system.web>
Fileupload control discussed well here.
http://weblogs.asp.net/jgalloway/archive/2008/01/08/large-file-uploads-in-asp-net.aspx
Try uploading along with file extension as below:
protected void Button1_Click(object sender, EventArgs e)
{
if (FileUpload1.HasFile) {
try
{
string filename = FileUpload1.FileName;
FileUpload1.SaveAs(Server.MapPath("~/Files/") + filename + System.IO.Path.GetExtension(FileUp.PostedFile.FileName);
Label1.Text = "File has been uploaded";
}
catch (Exception ex) {
Label1.Text = "The file could not be uploaded";
}
}
}
Related
I have a product page. I want to add my product to my database and I want also to update my product.
I have a problem with images.
When I insert the product everithing is ok.. In my aspx page I have this code:
<span>
<asp:FileUpload ID="files" runat="server" AllowMultiple="true" />
</span>
<div runat="server" id="previewImages"></div>
and when I save my product, in code behind I have this code:
string filenm = string.Empty;
HttpFileCollection fileCollection = Request.Files;
for (int i = 0; i < fileCollection.Count; i++)
{
HttpPostedFile uploadfile = fileCollection[i];
if (uploadfile.ContentLength > 0)
{
string filename = uploadfile.FileName;
System.IO.Directory.CreateDirectory(Server.MapPath("immScarpe/" + txtStyle.Text));
file.SaveAs(Server.MapPath("immScarpe/" + txtStyle.Text + "/") + fileName);
//this is pseudo-code
INSERT INTO PRODUCT_IMM (IdProduct, Path) VALUES (Id, "immScarpe/" + txtStyle.Text + "/" + fileName)
}
}
Now, the problem is that I can EDIT the saved product. When I click the edit button for a product, I have to load all it's data and let the user modify them. Also the images.
the main question is: How can I load the saved images in asp:FileUpload control?
Another thing I would like to do is to show images previews...in insert and in edit.
An Example of what I want to do is the thing that amazon does
but, if it's possible with only one FileUpload with AllowMultiple = true
I am willing to use other technologies like javascript, jquery and Ajax if it's necessary
Show Images Preview - Insert
<script src="jquery-1.10.1.min.js" type="text/javascript"></script>
<script type="text/javascript">
function ShowpImagePreview(input) {
if (input.files && input.files[0]) {
var reader = new FileReader();
reader.onload = function (e) {
$('#previewImage').attr('src', e.target.result);
}
reader.readAsDataURL(input.files[0]);
}
}
</script>
<asp:Image ID="previewImage" runat="server" />
<asp:FileUpload ID="FileUpload1" runat="server" onchange="ShowpImagePreview(this);" />
Here is a very basic example as to how you can handle images after they have been send to the server. In this snippet the filename of the image is fixed, but it should be enough to give you push in the right direction.
protected void Page_Load(object sender, EventArgs e)
{
//check if the file exists and show
if (File.Exists(Server.MapPath("testImage.jpg")))
{
setImage("/testImage.jpg");
}
}
//upload a new image
protected void Button1_Click(object sender, EventArgs e)
{
if (FileUpload1.HasFile)
{
try
{
FileUpload1.SaveAs(Server.MapPath("testImage.jpg"));
setImage("/testImage.jpg");
}
catch
{
//error writing file
}
}
}
//delete the image
protected void LinkButton1_Click(object sender, EventArgs e)
{
try
{
File.Delete(Server.MapPath("testImage.jpg"));
LinkButton1.Visible = false;
Image1.Visible = false;
}
catch
{
//error deleteing file
}
}
//set the image and show the delete link
private void setImage(string image)
{
Image1.ImageUrl = "/testImage.jpg";
Image1.Visible = true;
LinkButton1.Visible = true;
}
ASPX
<asp:Image ID="Image1" runat="server" Visible="false" />
<br />
<asp:LinkButton ID="LinkButton1" runat="server" Visible="false" OnClick="LinkButton1_Click">Delete image</asp:LinkButton>
<br />
<br />
<asp:FileUpload ID="FileUpload1" runat="server" />
<br />
<asp:Button ID="Button1" runat="server" Text="Upload" OnClick="Button1_Click" />
For displaying images to GridView from disk
https://www.aspsnippets.com/Articles/Display-Images-in-GridView-Control-using-the-path-stored-in-SQL-Server-database.aspx
Now you have the images shown, you want to have some replace or delete functionality on the images. You need to convert your field on the GridView for image to Template Field. You can do this by clicking on the source view of your ASPX page and replacing your ImageField or BoundField (whichever field you used in displaying the image).
See the design of the GridView on the question:
How to display image inside gridview template field without using handler class?
The way to bind the image source is in the answers in that question.
To have a delete or replace functionality, you can include a LinkButton control inside your TemplateField below the tag that displays the image.
You can set the LinkButton's CommandName property to 'Delete' or 'Replace' then on your .vb or .cs file, find the 'RowCommand' event for your GridView.
It goes something like (pseudo code only)
Protected Sub GridView_RowCommand(ByVal sender As Object, ByVal e As System.GridViewCommandEventArgs) Handles GridView.RowCommand
If e.CommandName = 'Delete' Then
'Place your delete query for your image record on the database here..
'Place your delete file from disk code here..
End If
End Sub
More info on GridView RowCommand Event
https://msdn.microsoft.com/en-us/library/system.web.ui.webcontrols.gridview.rowcommand(v=vs.110).aspx
I'm trying to make a simple uploadfile control with ASP.NET,
and it wouldnt work:
Here's my code(.aspx):
<form id="form1" runat="server">
<div>
upload a file now.
<asp:FileUpload ID="fileupload1" runat="server" />
<asp:Button ID="button1" Text="Upload" runat="server" Width="73px"
onclick="button1_Click" />
<asp:Label ID="Label1" runat="server" Font-Bold="True" ForeColor="#000099">
</asp:Label>
</div>
</form>
and here's my code behind(.cs):
if(fileupload1.HasFile)
{
try
{
if(fileupload1.PostedFile.ContentType == "image/jpeg")
{
if(fileupload1.PostedFile.ContentLength < 51200000)
{
string filename = Path.GetFileName(fileupload1.FileName);
fileupload1.SaveAs(Server.MapPath("~/img/") + filename);
Label1.Text ="File uploaded successfully!";
}
else
Label1.Text ="File maximum size is 500 Kb";
}
else
Label1.Text ="Only JPEG files are accepted!";
}
catch(Exception exc)
{
Label1.Text = "The file could not be uploaded. The following error occured: "
+ exc.Message;
}
}
the file is not presented in the server..
any thoughts?
when I breakpoint, they all goes valid, the application gets to the code, it all working , but won't save it to the folders.
This may or may not work entirely, but you need to include an enctype attribute in your form.
<form id="form1" runat="server" enctype="multipart/form-data">
If you don't do that, browsers won't transfer the file.
See here: https://developer.mozilla.org/en-US/docs/HTML/Element/form#attr-enctype
change
fileupload1.SaveAs(Server.MapPath("~/img/") + filename);
with
fileupload1.PostedFile.SaveAs(Server.MapPath("~/img/") + filename);
I think the problem lies in these two lines
string filename = Path.GetFileName(fileupload1.FileName);
fileupload1.SaveAs(Server.MapPath("~/img/") + filename);
why are you using
string filename = Path.GetFileName(fileupload1.FileName);
It should be simple
fileupload1.SaveAs(Server.MapPath("~/img/") + fileupload1.FileName);
I am working with a fileuploader to upload a picture. However, evertyime i select the file and click the upload button it says that the fileuploader.file returns a value of false and does not run the next lines of code. All i can find is that it has to be in in a seperate form and that the method has to be "post", but that did not fix the problem.
here is my codebehind.
if (FileUploadControl.HasFile)
{
try
{
string filename = Path.GetFileName(FileUploadControl.FileName);
FileUploadControl.SaveAs(Server.MapPath("~/") + filename);
StatusLabel.Text = "Upload status: File uploaded!";
}
catch (Exception ex)
{
StatusLabel.Text = "Upload status: The file could not be uploaded. The following error occured: " + ex.Message;
}
}
here is my front end code.
<form id="form2" action="CompProfile.aspx" method="post" enctype="multipart/form-data">
<asp:FileUpload id="FileUploadControl" runat="server" />
<asp:Button runat="server" id="UploadButton" text="Upload" onclick="UploadButton_Click" />
<asp:Label runat="server" id="StatusLabel" text="Upload status: " />
</form>
If you are testing with a 0 byte sized file it will return false. Make sure the file actually isn't empty.
Your form should have runat="server" instead of method="post" and action="..."
I am trying to upload an image and after uploading i want to show it in the image control. My code is:
<form id="form1" runat="server">
<div>
<asp:ScriptManager ID="ScriptManager1" runat="server">
</asp:ScriptManager>
<asp:UpdatePanel ID="UpdatePanel1" runat="server">
<ContentTemplate>
<asp:FileUpload ID="FileUploadTest" runat="server" />
<asp:Button ID="ShowImage" runat="server" Text="Show"
onclick="ShowImage_Click" />
<asp:Image ID="ImageUploaded" runat="server" Height="150px" Width="150px"
ImageUrl="~/images/blankImage.gif" />
<asp:Label ID="Label1" runat="server" Text=""></asp:Label>
</ContentTemplate>
<Triggers>
<asp:PostBackTrigger ControlID="ShowImage" />
</Triggers>
</asp:UpdatePanel>
</div>
</form>
C# code is:
protected void ShowImage_Click(object sender, EventArgs e)
{
Label1.Text = "";
if (FileUploadTest.HasFile)
{
try
{
if (FileUploadTest.PostedFile.ContentType == "image/jpeg")
{
if (FileUploadTest.PostedFile.ContentLength < 102400)
{
string filename = Path.GetFileName(FileUploadTest.FileName);
string imageSavePath = Server.MapPath("~/images/") + filename;
FileUploadTest.SaveAs(imageSavePath);
ImageUploaded.ImageUrl = imageSavePath;
ImageUploaded.Visible = true;
Label1.Text = "Upload status: File uploaded!";
}
else
Label1.Text = "Upload status: The file has to be less than 100 kb!";
}
else
Label1.Text = "Upload status: Only JPEG files are accepted!";
}
catch (Exception ex)
{
Label1.Text = "Upload status: The file could not be uploaded. The following error occured: " + ex.Message;
}
}
else
{
Label1.Text = "No File !!!";
}
}
But After pressing the show button, the image is uploaded successfully. But the image control got vanished. Can any one help me about it?
Your problem is simply that you have the wrong URL for the image after it is uploaded. Change your code to this:
ImageUploaded.ImageUrl = "~/images/" + filename;
I am trying to upload an image and after uploading i want to show it in the image control. My code is:
<form id="form1" runat="server">
<div>
<asp:ScriptManager ID="ScriptManager1" runat="server">
</asp:ScriptManager>
<asp:UpdatePanel ID="UpdatePanel1" runat="server">
<ContentTemplate>
<asp:FileUpload ID="FileUploadTest" runat="server" />
<asp:Button ID="ShowImage" runat="server" Text="Show"
onclick="ShowImage_Click" />
<asp:Image ID="ImageUploaded" runat="server" Height="150px" Width="150px"
ImageUrl="~/images/blankImage.gif" />
<asp:Label ID="Label1" runat="server" Text=""></asp:Label>
</ContentTemplate>
<Triggers>
<asp:PostBackTrigger ControlID="ShowImage" />
</Triggers>
</asp:UpdatePanel>
</div>
</form>
C# code is:
protected void ShowImage_Click(object sender, EventArgs e)
{
Label1.Text = "";
if (FileUploadTest.HasFile)
{
try
{
if (FileUploadTest.PostedFile.ContentType == "image/jpeg")
{
if (FileUploadTest.PostedFile.ContentLength < 102400)
{
string filename = Path.GetFileName(FileUploadTest.FileName);
string imageSavePath = Server.MapPath("~/images/") + filename;
FileUploadTest.SaveAs(imageSavePath);
ImageUploaded.ImageUrl = imageSavePath;
ImageUploaded.Visible = true;
Label1.Text = "Upload status: File uploaded!";
}
else
Label1.Text = "Upload status: The file has to be less than 100 kb!";
}
else
Label1.Text = "Upload status: Only JPEG files are accepted!";
}
catch (Exception ex)
{
Label1.Text = "Upload status: The file could not be uploaded. The following error occured: " + ex.Message;
}
}
else
{
Label1.Text = "No File !!!";
}
}
But After pressing the show button, the image is uploaded successfully. But the image control got vanished. Can any one help me about it?
I think you have to set image url to a valid url. Check the result of your Server.MapPath method.
You have to set an URI location to your image.
Morzel