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

标签 asp.net html 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>

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 文件。无法查看保存的文件。出了什么问题?

最佳答案

您需要像这样添加 idrunat="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/

相关文章:

file-upload - apache commons fileupload 是否支持分块上传?

javascript - 为什么这个正则表达式不起作用即使它是有效的并且在测试代码上运行良好

c# - REGEX 停止目录遍历

asp.net - 在 Azure 云服务中启用共置 session 缓存

html - Div 布局问题 - 无法让标题随页面放大/缩小

javascript - 使用 .append() + css/styling 使用 Jquery/Javascript 添加新文本

html - 当旁边有一个 <img/> 时,如何让我的 <h1> 居中?

c# - ASP.NET:Eval 中的对象

javascript - ReferenceError StringBuilder 未在 JavaScript 中定义

javascript - 使用 accept 捕获的 Polyfill 文件输入(使用 getUserMedia 捕获?)