Uploading MS WORD ( DOC / DOCX ) FILES IN ASP.NET
In previous post we have seen simple example for uploading files in ASP.NET. And in this post we will see uploading files of particular type. We have to filter the file type based on its Content Type(MIME type). Here I am discussing about uploading doc/docx files in asp.net. Add a new folder “uploads” to your asp website. Because in this example we are uploading files to the Upload folder in our Asp Application. First take a upload control on Default.aspx, the code is give below.
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 |
<html xmlns="http://www.w3.org/1999/xhtml"> <head runat="server"> <title></title> </head> <body> <form id="form1" runat="server"> <asp:FileUpload ID="FileUpload1" runat="server" /> <br /> <br /> <asp:Label ID="lblMessage" runat="server"></asp:Label> <br /> <br /> <asp:Button ID="btnSubmit" runat="server" onclick="btnSubmit_Click" Text="Submit" /> </form> </body> </html> |
The C# code in the code behind file is given below :
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 |
using System; public partial class _Default : System.Web.UI.Page { protected void Page_Load(object sender, EventArgs e) { } protected void btnSubmit_Click(object sender, EventArgs e) { string path = Server.MapPath("." + "\uploads\" + FileUpload1.FileName); if (FileUpload1.HasFile) { lblMessage.Text=FileUpload1.PostedFile.ContentType; if (System.IO.File.Exists(path)) { Response.Write("Already exists"); } else { if (FileUpload1.PostedFile.ContentType == "application/vnd.openxmlformats-officedocument.wordprocessingml.document" || FileUpload1.PostedFile.ContentType=="application/msword") { FileUpload1.SaveAs(path); Response.Write("Upload successful"); } else { Response.Write("Invalid file format"); } } } else { Response.Write("please select file"); } } } |
See the images below:
When a ms word file is uploaded:
When a file other than ms word file:
[…] Previous posts i have explained about simple example for UPLOADING FILES IN ASP.NET and UPLOADING DOC / DOCX FILES IN ASP.NET . Actually the default maximum size of files that can be uploaded in ASP.NET is 4MB ( […]