访问输入类型的文件在asp.net服务器端 [英] Accessing input type file at server side in asp.net
问题描述
我使用的是<输入类型=文件/>
标签来上传文件到服务器。我如何在服务器端访问该文件,并将其存储在服务器上? (该文件是图像文件)
I am using the <input type="file" />
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 file is an image file)
客户端code是:
<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有
Photostore.aspx.cs has
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文件。无法看到保存的文件。这是怎么回事了?
I tried uploading a jpg file. Not able to see a saved file. What is going wrong?
推荐答案
您需要添加 ID
和 =服务器
属性是这样的:
You'll need to add id
and runat="server"
attributes like this:
<input type="file" id="MyFileUpload" runat="server" />
然后,在服务器端,你将有机会获得控件的<一个href=\"http://msdn.microsoft.com/en-us/library/system.web.ui.htmlcontrols.htmlinputfile.postedfile.aspx\"><$c$c>PostedFile$c$c>属性,它会给你一个< href=\"http://msdn.microsoft.com/en-us/library/system.web.httppostedfile.contentlength.aspx\"><$c$c>ContentLength$c$c>, <一href=\"http://msdn.microsoft.com/en-us/library/system.web.httppostedfile.contenttype.aspx\"><$c$c>ContentType$c$c>, <一href=\"http://msdn.microsoft.com/en-us/library/system.web.httppostedfile.filename.aspx\"><$c$c>FileName$c$c>, <一href=\"http://msdn.microsoft.com/en-us/library/system.web.httppostedfile.inputstream.aspx\"><$c$c>InputStream$c$c>特性和<一href=\"http://msdn.microsoft.com/en-us/library/system.web.httppostedfile.saveas.aspx\"><$c$c>SaveAs$c$c>方法等:
int contentLength = MyFileUpload.PostedFile.ContentLength;
string contentType = MyFileUpload.PostedFile.ContentType;
string fileName = MyFileUpload.PostedFile.FileName;
MyFileUpload.PostedFile.Save(@"c:\test.tmp");
另外,你可以使用<一个href=\"http://msdn.microsoft.com/en-us/library/system.web.htt$p$pquest.files.aspx\"><$c$c>Request.Files$c$c>它给你所有上传文件的集合:
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++;
}
这篇关于访问输入类型的文件在asp.net服务器端的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!