在asp.net中访问服务器端的输入类型文件

Aja*_*jay 5 html asp.net file-upload

我正在使用<input type="file" />标签将文件上传到服务器.如何在服务器端访问该文件并将其存储在服务器上?(该文件是图像文件)

客户端代码是:

<form id="form1" action="PhotoStore.aspx" enctype="multipart/form-data">
    <div>
    <input type="file" id="file" onchange="preview(this)" />
    <input type="submit" />
    </div>
</form>
Run Code Online (Sandbox Code Playgroud)

Photostore.aspx.cs有

protected void Page_Load(object sender, EventArgs e)
        {
            int index = 1;
            foreach (HttpPostedFile postedFile in Request.Files)
            {
                int contentLength = postedFile.ContentLength;
                string contentType = postedFile.ContentType;
                string fileName = postedFile.FileName;

                postedFile.SaveAs(@"c:\test\file" + index + ".tmp");

                index++;
            } 

        }
Run Code Online (Sandbox Code Playgroud)

我试过上传一个jpg文件.无法查看已保存的文件.出了什么问题?

Luk*_*keH 7

你需要添加id和这样的runat="server"属性:

<input type="file" id="MyFileUpload" runat="server" />
Run Code Online (Sandbox Code Playgroud)

然后,在服务器端,你将有机会获得该控件的PostedFile属性,它会给你ContentLength,ContentType,FileName,InputStream属性和SaveAs方法等:

int contentLength = MyFileUpload.PostedFile.ContentLength;
string contentType = MyFileUpload.PostedFile.ContentType;
string fileName = MyFileUpload.PostedFile.FileName;

MyFileUpload.PostedFile.Save(@"c:\test.tmp");
Run Code Online (Sandbox Code Playgroud)

或者,您可以使用Request.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++;
}
Run Code Online (Sandbox Code Playgroud)

  • 如果您不想使用服务器控件,那么您可以使用`Request.Files`,它将为您提供包含每个上传文件的`HttpPostedFile`对象的集合. (3认同)

Dim*_*kis 0

查看 ASP.NET 提供的 asp:FileUpload 控件。