ajaxfileupload cant work.ajaxfileupload destroy everthing - c#

 I'm using ajaxfileupload right now. After uploading a file with ajaxfileupload, I want to save it to D:folder with saveas.
I use C# and asp.net.I use aspx and aspx.cs. Ajaxfileupload is in ajaxtoolkit in asp.net.
 When I saveas with ajaxfileupload, it is indeed saved to a folder. But I can't open it. The file seems to be corrupted. Actually, it is to upload JPG, but when I tried uploading Word and PowePoint, it also broke.
 
 The JPG remains corrupted, but Word and PowerPoint can choose to repair and let the file show its contents. Why can't I get the jpg to be displayed, and doing saveas with ajaxfileupload corrupts all the files? Does AjaxFileUpload destroy everything?
 I'm afraid I'm about to be broken by ajaxfileupload until then...Please help me.

The file should be saved just fine. Remember any web based URL will map to a sub folder inside of your root project.
In other words, with code behind, you can as a general rule save the file to ANY location on the computer. However, that will NOT allow web based URL's to map and directly use such files.
So, your web site folders should look like this:
So, add, or create folder - but it in most cases should be inside of the root folder of your web site (it does not have to be).
So, now lets drop in our ajaxfile up, and let the user up-load some files.
Say, this markup:
<div style="width:35%">
<ajaxToolkit:AjaxFileUpload ID="AjaxFileUpload1" runat="server"
OnUploadComplete="AjaxFileUpload1_UploadComplete"
OnClientUploadCompleteAll="clickdone" />
</div>
<script>
function clickdone() {
$('#cmdDone').click();
}
</script>
<asp:Button ID="cmdDone" runat="server" Text="Done upload"
OnClick="cmdDone_Click" ClientIDMode="Static" CssClass="btn"/>
Note VERY close in above. We dropped in a button, and we CLICK this button after all files are up-loaded. The ajax fileupload does NOT do a post-back after we are done up-loading the files. (and we want/need a final post-back of the page).
So, I added a ".click()" to the file upload with this:
OnClientUploadCompleteAll="clickdone()"
That simple clicks on our button.
Ok, now we need/want to display the files after the up-load.
so, right below above markup, I dropped in a grid view, but with dispay:none, it will be hidden until all files are done.
So we have this gridview:
<div id="myfiles" runat="server" style="width: 45%; display: none">
<asp:GridView ID="GridFiles" runat="server"
AutoGenerateColumns="False" ShowHeaderWhenEmpty="true" CssClass="table">
<Columns>
<asp:BoundField DataField="FileName" HeaderText="FileName" />
<asp:BoundField DataField="UpLoadTime" HeaderText="UpLoaded" />
<asp:TemplateField HeaderText="Preview">
<ItemTemplate>
<asp:Image ID="Image1" runat="server" Width="140px"
ImageUrl='<%# Eval("SavePath") %>' />
</ItemTemplate>
</asp:TemplateField>
<asp:TemplateField HeaderText="Download" ItemStyle-HorizontalAlign="Center">
<ItemTemplate>
<asp:Button ID="cmdDownLoad" runat="server" Text="Download" CssClass="btn" OnClick="cmdDownLoad_Click" />
</ItemTemplate>
</asp:TemplateField>
</Columns>
</asp:GridView>
</div>
And we have a table like this:
So, we now have this - we select some files:
And after we hit up-load, we see/get this:
Ok, so now all we need is the one up-load "one file" event for the ajax file upload, and that code is this:
protected void AjaxFileUpload1_UploadComplete(object sender, AjaxControlToolkit.AjaxFileUploadEventArgs e)
{
// save file to up-loads folder
string strSaveFile = Server.MapPath(#"~/UpLoadFiles/" + e.FileName);
string strURL = #"~/UpLoadFiles/" + e.FileName;
AjaxFileUpload1.SaveAs(strSaveFile);
// now add this row to data base
string strSQL = "INSERT INTO MyUpLoadFiles (FileName, Size, UpLoadTime, User_ID, SavePath) " +
"VALUES (#FileName, #Size, #UpLoadTime, #User_ID, #SavePath)";
using (SqlConnection conn = new SqlConnection(Properties.Settings.Default.TEST4))
{
using (SqlCommand cmdSQL = new SqlCommand(strSQL, conn))
{
cmdSQL.Parameters.Add("#FileName", SqlDbType.NVarChar).Value = e.FileName;
cmdSQL.Parameters.Add("#Size", SqlDbType.Int).Value = e.FileSize;
cmdSQL.Parameters.Add("#UpLoadTime", SqlDbType.DateTime).Value = DateTime.Now;
cmdSQL.Parameters.Add("User_ID", SqlDbType.Int).Value = Session["User_ID"];
cmdSQL.Parameters.Add("#SavePath", SqlDbType.NVarChar).Value = strURL;
conn.Open();
cmdSQL.ExecuteNonQuery();
}
}
}
And our button click (that fires after up-load) is this:
protected void cmdDone_Click(object sender, EventArgs e)
{
myuploader.Style.Add("display", "none"); // hide up-loader
myfiles.Style.Add("display", "normal"); // show my files grid
GridFiles.DataSource = MyRst("SELECT * FROM MyUpLoadFiles ORDER BY UpLoadTime DESC");
GridFiles.DataBind();
}
Once this is working, then we can (should) hide that button - since after up-loading, we don't want the user to have to click that "done" button to display the files.
And in the gridview, the download button can look like this:
protected void cmdDownLoad_Click(object sender, EventArgs e)
{
Button myBut = sender as Button;
GridViewRow gRow = myBut.NamingContainer as GridViewRow;
string strFileOnly = gRow.Cells[0].Text;
string strFile = "";
strFile = Server.MapPath(#"~/UpLoadFiles/" + strFileOnly);
string sMineType = MimeMapping.GetMimeMapping(strFileOnly);
Response.ContentType = sMineType;
Response.AppendHeader("Content-Disposition", "attachment; filename=" + strFileOnly);
Response.TransmitFile(strFile);
Response.End();
}
Now, you have to decide "where" you going to save those files. If you save into a folder OUTSIDE of the web folders, then you cannot use a simple "url" for the file name to download as I did. You can STILL do this, and often this setup is desirable, since when the folder is OUTSIDE of the web folders, then no valid URL's directly mapped to the file(s) exists, and this is VERY good for security. But, then that means the download button, and even display/preview of the files has to be done in a different way (you have to stream the files, and you can use transmit file as I did, but the path names will be different. And if you want a preview in the grid, you ALSO have to stream the file to that image control.
So VERY much keep in mind:
URL - for web and markup = valid path name based on realative to the web site.
Code behind: ALWAYS will use a plane jane full windows path name. So, you have to be aware of this difference in how web based URL's work with a file as opposed to code behind which ALWAYS will use a plane jane full windows path name.
As for file corruption? No, I am not seeing nor experiencing this. You might want to edit your answer, and show your save code for the file up-load event you have. You don't show how you are downloading the file. I suppose you could open that MyUpLoadFiles folder directly, and see if the file is corrupter, but I not experience that issue.

Related

How to make ASP.NET File Upload control works within ASP.NET Wizard control?

I am a new .NET developer and I am enhancing an existing legacy ASP.NET Web Forms application where I am trying to use ASP.NET File Upload control within ASP.NET Wizard control. The File Upload control is in an ASP.NET User Control which I am using in different pages across the application. This user control works well in all pages except the current page that includes a Wizard control. I am loading the (File Upload) user control within one of the Wizard steps through OnLoad() method of the wizard. I am currently encountering a strange behavior with the file upload functionality:
Upon selecting a file to upload and click on Upload button the file path will be lost in the OnClick button method. However, if I select the file again and click on Upload button for the second time, the file will be uploaded successfully!!!!!!!!!
Code of asp.net user control that includes the file upload control:
<asp:UpdatePanel ID="UpdatePanel1" runat="server">
<ContentTemplate>
<asp:FileUpload ID="FileUpload1" runat="server" EnableViewState="true" ViewStateMode="Enabled"></asp:FileUpload>
<asp:LinkButton ID="lbtnUpload" runat="server" OnClick="lbtnUpload_Click" Text="Upload">
</asp:LinkButton>
</ContentTemplate>
<Triggers>
<asp:PostBackTrigger ControlID="lbtnUpload" />
</Triggers>
</asp:UpdatePanel>
Code-behind of User Control:
protected void lbtnUpload_Click(object sender, EventArgs e)
{
// Check File Prasent or not. Problem: In First OnClick, It will give false
// After selecting the file for second time and click on Upload button, it will return true!!!!
if (FileUpload1.HasFiles)
{
//Save uploaded file to the server
}
}
Code of ASPX page that includes our wizard control where I am dynamically loading the file upload user control in one of the wizard steps:
<asp:Wizard ID="Wizard1" runat="server" EnableViewState="true" ViewStateMode="Enabled"
OnLoad="Wizard1_Load">
<WizardSteps>
<asp:WizardStep ID="WizardStep1" runat="server" Title="File Upload">
<asp:PlaceHolder ID="PlaceHolder1" runat="server"></asp:PlaceHolder>
</asp:WizardStep>
</WizardSteps>
</asp:Wizard>
and here is the code behind of the ASPX page
protected void Wizard1_Load(object sender, EventArgs e)
{
PlaceHolder PlaceHolder1= wzServiceOrder.FindControl("PlaceHolder1") as PlaceHolder;
if (PlaceHolder1!= null)
{
Control ucFileUpload = PlaceHolder1.FindControl("ucFileUpload ") as Control;
if (ucFileUpload == null)
{
ucFileUpload = LoadControl("~/Controls/FileUpload.ascx");
PlaceHolder1.Controls.Add(ucFileUpload);
}
}
}
Any help on how to make the file upload works from the first click on the Upload button?

Show video file in listview keep download option in asp.net

My concept is about stegnography. I want to play the video file and keep the download option. If the client clicks the download button, the video along with registration message should download.
I used the following code
in .cs
DirectoryInfo dir = new DirectoryInfo(MapPath("~/Video"));
FileInfo[] files = dir.GetFiles();
ArrayList listItems = new ArrayList();
foreach (FileInfo info in files)
{
listItems.Add(info);
}
DataList1.DataSource = listItems;
DataList1.DataBind();
in design
Font-Names="Verdana" Font-Size="Small" RepeatColumns="3" RepeatDirection="Horizontal"
Width="600px" ForeColor="#333333">
<ItemTemplate>
<br />
<b>Song Name:</b>
<asp:Label ID="lblCName" runat="server" Text='<%# Bind("name") %>'></asp:Label>
<br />
<video controls="controls" width="200" height="200" src='<%# Eval ("name","Video/{0}") %>'></video>
<br />
<b>Download:</b>
<asp:LinkButton ID="LinkButton1" runat="server" Text='<%#Eval("name") %>'></asp:LinkButton>
here download option is not working, can any 1 give some idea for this plz.
The best[*] way to download a big file, like a video, is to use a handler.
So you create a handler that send the file and you send the parametres of what file to download on the url. For example you can do something like:
<b>Download:</b> <a target="_blank" href="download.ashx?name=<%#Eval("name") %>'>"><%#Eval("name") %>'></a>
And on the handler download.ashx you read the parameter "name" and you send that file.
This also can help you:
What is the best way to download file from server
asp.net ashx handler prompting download instead of displaying file
files download using HTTP Handler
[*]Why is the best way to use a hander ?:
Have the minimum of code compare with an aspx page.
Have clear return - Send only what you render on output.
Did not use session, so did not felt into the session lock and you avoid time outs

How can I force <a> links to files trigger download in the browser (and not open)

I knowt it may be a repeated question but I couldn't find a solution to my case.
Here's what I am doing:I want to create a page where admin of the site can upload files and make a description for each file,and then users can download these files.I created an admin page with a fileupload control that saves the files in downloads/files.Then I created a database with three columns: 1-downloadtitle 2-downloadmain 3-name.The admin can enter download title and download main(the description of the file) for each file.and the name column will be filled automatically with the uploaded file's name.
Now here is what I did for the download page(after getting the data from the database using code behind):
<asp:Repeater ID="downloadsRepeater" runat="server">
<ItemTemplate>
<div class="downloadTitle"><%#Eval("downloadtitle") %></div>
<div class="downloadMain"><%#Eval("downloadmain") %>
<div class="downloadButtom" dir="ltr">Download</div>
</div>
</ItemTemplate>
<SeparatorTemplate>
<div class="separator"></div>
</SeparatorTemplate>
</asp:Repeater>
You can get the idea of how the page looks form the above code(I don't want the download links to redirect the user to another page.I want users to just click the download and the the file gets downloaded!)
This method I used is working with doc files, but it is not working for PDF files for example!(Pdf files will be opened by the browser instead of download)
So I want to know if theyre's a way of doing this the way I want it?
As far as I know it is not possible by just setting some special string to the href property of an <a> tag.
But you can get your desired behaviour by replacing the link by an asp.net linkbutton and a postback in which you call the following method:
public static void DownloadFile(string filename, string path)
{
Response.ContentType = "application/unknown";
Response.AppendHeader("Content-Disposition", "attachment; filename=" + filename);
Response.TransmitFile(path);
Response.End();
}
path is the full path to the file you want to send to the client and filename is the name which the file should have when it is sent (can be different from the original name).
Make the html hyperlink runat ="server"

Issue with asp Image and file upload controls in Mozilla Firefox

I have an Image control which is used to display image on click of a button. The code is as below:
.aspx code
<asp:Image ID="imgCorrect" runat="server" Height="175px" Width="150px" ImageUrl="~/_layouts/images/NoPreviewShareHR_Grey.jpg" />
<asp:FileUpload ID="FlUpldImage" runat="server" Width="200px" />
<asp:RegularExpressionValidator runat="server" ID="valUp" ControlToValidate="FlUpldImage"
ErrorMessage="Image Files Only (.jpg, .bmp, .png, .gif)" ValidationGroup="ImageFormat"
ValidationExpression="^(([a-zA-Z]:)|(\\{2}\w+)\$?)(\\(\w[\w].*))(.jpg|.JPG|.gif|.GIF|.jpeg|.JPEG|.bmp|.BMP|.png|.PNG)$" />
<asp:Button ID="btnImageUpload" runat="server" Text="Preview" OnClick="btnImageUpload_Click" CausesValidation="false"/>
<asp:HiddenField ID="HidnLocalImageURL" runat="server" Value=""/>
C# Code
protected void btnImageUpload_Click(object sender, EventArgs e)
{
String fileToUpload = Convert.ToString(FlUpldImage.PostedFile.FileName);
HidnLocalImageURL.Value = fileToUpload;
if (fileToUpload != "")
imgCorrect.ImageUrl = fileToUpload;
else
imgCorrect.ImageUrl = "~/_layouts/images/NoPrview.jpg";
}
The above code works fine on IE but gives issue in Mozilla Firefox:
The RE validator for file upload shows error message as invalid image even if proper
image is selected and
onclick of btnImageUpload the image control disappears. This
issue occurs on Firefox browser only and works fine in IE.
fileToUpload in C# code contains the prope path to the image including drive letter. I don't want to physically store the files into application folder as this is just to preview the image.
Kindly help me to sort out both issues.
Try to log FlUpldImage.PostedFile.FileName.
I think firefox sends only filename not full path.
If so, its better to use simple textbox and paste path in it without dialogbox.
As a security precaution, references to images on your local computer from a remote web site are disabled. If you encounter this restriction and you understand the security implications, you can disable this security measure.
for more info
http://kb.mozillazine.org/Images_or_animations_don%27t_load

Upload a file to server automatically inside a update panel in asp.net website

I have a file upload inside the update panel, and an upload button that uploads the file to the server. Is it possible to upload the file without clicking the upload button? I want to remove the upload button and upload the file as soon as the file is selected from the user's machine. Or, have a 4 second timer, then call the upload_click to check if the fileupload has a file or not. How can I do it without a button inside update panel?
<asp:UpdatePanel ID="UP_DDL" runat="server" UpdateMode="Always" ChildrenAsTriggers="true">
<ContentTemplate>
<asp:FileUpload ID="FileUpload1" runat="server" />
<asp:Button ID="Upload" OnClick="Upload_Click" runat="server" Text="Upload" />
</ContentTemplate>
<Triggers>
<asp:PostBackTrigger ControlID="Upload"/>
</Triggers>
</asp:UpdatePanel>
protected void Upload_Click(object sender, EventArgs e)
{
if (FileUpload1.HasFile)
{
//create the path to save the file to
string fileName = Path.Combine(Server.MapPath("~/Bulk Upload"), FileUpload1.FileName);
//save the file to our local path
FileUpload1.SaveAs(fileName);
}
}
I am sure you can use any of the events on the HTML INPUT File element to fire up a full post back, which is all you need in order to upload the file automatically.
Google, at least on the standard interface, uses some sort of Flash plugin to accomplish what you want.
There might be some other jQuery plugins that provide this functionality out of the box. This one, for example, seems to do it.
You would need to mimic the click with some client-side code, such as using submit from Javascript - and this is not supported by at least one notable browser, I believe, IE.
Otherwise, you could use jQuery ajax calls to static web methods which do uploads on the fly, behind the scenes, when the value of the file upload control have changed.
You can hide Upload button with display:none inline style and add following code to Page_PreRender method:
FileUpload1.Attributes["onchange"] = ClientScript.GetPostBackClientHyperlink(Upload, "");
Or consider to use AsyncFileUpload control from AjaxControlToolkit

Categories