How can I upload a file to a server in asp.net

I have 2 pages send.aspx

and recive.aspx

.

In send.aspx

I have FileUpload

and Button

that post the selected file to the page recive.aspx

.

Below you can see the recive.aspx.cs

code at Page_Load

the end.

How do I submit a file to this page?

 protected void Page_Load(object sender, EventArgs e)
    {
        string action = Request.Params["action"];

        if (action == null)
        {
            Response.StatusCode = 400;
            Response.End();
        }


        if (action.Equals("upload"))
        {
            HttpPostedFile file = Request.Files["file"];
            if (file != null && file.ContentLength > 0)
            {
                //string guid = Guid.NewGuid().ToString();
                string ext = Path.GetExtension(file.FileName);
                //2- Get and check file extension
                string[] validExtesions = { ".e", ".jpg", ".gif", ".png", ".rar",
                ".zip",".3gp",".3gpp",".mp4",".mov",".wmv",".avi", "",".jpeg", ".mp3", ".ogg"};

                if (Array.IndexOf(validExtesions, ext.ToLower()) < 0)
                {
                    Response.Write("Invalid file extension!");
                    Response.End();
                }
                //3- Get and check file size
                long fileSize = file.ContentLength;
                fileSize /= 1024;
                if (fileSize > 2048000)
                {
                    Response.Write("Fiele size must be < 2GB");
                    Response.End();
                }
                //4- Get file name
                string fileName = Path.GetFileName(file.FileName);
                //5- Check file exist and if (true) generate new name
                while (File.Exists(Path.Combine(UploadFolder, fileName)))
                    fileName = "1" + fileName;
                string fname = fileName;
                string path = Server.MapPath(Path.Combine(UploadFolder, fname));


                file.SaveAs(path);

                Response.Write(fname);
                Response.End();
            }
            else
            {
                Response.StatusCode = 400;
                Response.End();
            }
        }


    }

      

+3


source to share





All Articles