我正在使用 <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>
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++;
}
}
我尝试上传一个 jpg 文件。无法查看保存的文件。出了什么问题?
最佳答案
您需要像这样添加 id
和 runat="server"
属性:
<input type="file" id="MyFileUpload" runat="server" />
然后,在服务器端您可以访问控件的 PostedFile
属性(property),这会给你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");
或者,您可以使用 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++;
}
关于asp.net - 在 asp.net 中访问服务器端的输入类型文件,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/1998452/