Question

I am trying to upload video file in a folder using HttpFileCollection but it appears that it is not getting saved in the folder. It is giving an error that it cannot find the path although the path is correct. This is my code

   <form id="form1" runat="server">
<div>

    <asp:Image ID="Image1" ImageUrl="~/ProductVideos/" runat="server" Width="118px" />

</div>
    <asp:FileUpload ID="FileUpload1" runat="server" />
    <asp:Button ID="Button1" runat="server" OnClick="Button1_Click" Text="Button" />
</form>

C# Code:

   protected void Button1_Click(object sender, EventArgs e)
    {
        UploadVideoToFolder();
    }

     public string UploadVideoToFolder()
    {
        string vTitle = "";
        string vDesc = "";
        string FilePath = HttpContext.Current.Server.MapPath("~/ProductVideos/" + HttpContext.Current.Request.Form["title"]);



        HttpFileCollection MyFileCollection = HttpContext.Current.Request.Files;
        if (MyFileCollection.Count > 0)
        {
            // Save the File
            try
            {
                MyFileCollection[0].SaveAs(FilePath);
                return "1";
            }
            catch (Exception ex)
            {
                return "-1";
            }
        }
        else
            return "-1";

Help me do this please.

Was it helpful?

Solution

Try this code.

        string filename = Path.GetFileName(FileUpload1.FileName);
        HttpFileCollection MyFileCollection = HttpContext.Current.Request.Files;
        if (MyFileCollection.Count > 0)
        {
            try
            {
                MyFileCollection[0].SaveAs(Server.MapPath("~/ProductVideos/") + filename);

             }
            catch (Exception ex)
            {

            }
        }

OTHER TIPS

Refer Following Code:

You will have to add for loop in your code as follows:

HttpFileCollection MyFileCollection  = Request.Files;
for (int i = 0; i < MyFileCollection .Count; i++)
{
    HttpPostedFile httpPostedFile = MyFileCollection [i];
    if (httpPostedFile.ContentLength > 0 )

    {

    }
}
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top