加入收藏 | 设为首页 | 会员中心 | 我要投稿 李大同 (https://www.lidatong.com.cn/)- 科技、建站、经验、云计算、5G、大数据,站长网!
当前位置: 首页 > 编程开发 > asp.Net > 正文

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

发布时间:2020-12-16 00:15:00 所属栏目:asp.Net 来源:网络整理
导读:我正在使用 input type =“file”/标记以将文件上载到服务器.如何在服务器端访问该文件并将其存储在服务器上? (该文件是图像文件) 客户端代码是: form id="form1" action="PhotoStore.aspx" enctype="multipart/form-data" div input type="file" id="file
我正在使用< 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:testfile" + index + ".tmp");

                index++;
            } 

        }

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

解决方法

您需要添加id和runat =“server”属性,如下所示:
<input type="file" id="MyFileUpload" runat="server" />

然后,在服务器端,您将可以访问控件的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");

或者,您可以使用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++;
}

(编辑:李大同)

【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容!

    推荐文章
      热点阅读