Accessing input type file at server side in asp.net

后端 未结 5 497
别跟我提以往
别跟我提以往 2021-01-03 02:57

I am using the tag to upload a file to the server. How do I access the file at the server side and store it at the server? (The fi

相关标签:
5条回答
  • 2021-01-03 03:25

    I think the name tag is required on the file input:

    <input type="file" name="file" />
    

    Without this, I don’t get anything back.


    Further problems that I had which might be specific to my machine:

    I get a

    Unable to cast object of type 'System.String' to type 'System.Web.HttpPostedFile'.
    

    error at the line

    foreach (HttpPostedFile postedFile in Request.Files)
    

    so my final code looks like this:

    for (var i = 0; i < Request.Files.Count; i++)
    {
        var postedFile = Request.Files[i]; 
    
        // do something with file here
    }
    
    0 讨论(0)
  • 2021-01-03 03:26

    Look into the asp:FileUpload control provided by ASP.NET.

    0 讨论(0)
  • 2021-01-03 03:28

    If you dont want to use the FileUpload control in the toolbox, Give your input an ID then use form[id] to access the input field and cast it to HtmlInputFile.

    example here: http://www.codeproject.com/KB/aspnet/fileupload.aspx

    0 讨论(0)
  • 2021-01-03 03:32

    If you give the input-tag an id and add the runat="server" attribute then you can access it easily.
    First change your input tag: <input type="file" id="FileUpload" runat="server" />
    Then add the following to your Page_Load method:

    if (FileUpload.PostedFile != null) 
    {
      FileUpload.PostedFile.SaveAs(@"some path here");
    }
    

    This will write your file to a folder of your choice. You can access the PostedFile object if you need to determine the file type or original file name.

    0 讨论(0)
  • 2021-01-03 03:39

    You'll need to add id and runat="server" attributes like this:

    <input type="file" id="MyFileUpload" runat="server" />
    

    Then, on the server-side you'll have access to the control's PostedFile property, which will give you ContentLength, ContentType, FileName, InputStream properties and a SaveAs method etc:

    int contentLength = MyFileUpload.PostedFile.ContentLength;
    string contentType = MyFileUpload.PostedFile.ContentType;
    string fileName = MyFileUpload.PostedFile.FileName;
    
    MyFileUpload.PostedFile.Save(@"c:\test.tmp");
    

    Alternatively, you could use Request.Files which gives you a collection of all uploaded files:

    int index = 1;
    foreach (HttpPostedFile postedFile in Request.Files)
    {
        int contentLength = postedFile.ContentLength;
        string contentType = postedFile.ContentType;
        string fileName = postedFile.FileName;
    
        postedFile.Save(@"c:\test" + index + ".tmp");
    
        index++;
    }
    
    0 讨论(0)
提交回复
热议问题