【问题标题】:How to get File Stream from a custom FileUpload in asp.net?如何从 asp.net 中的自定义 FileUpload 获取文件流?
【发布时间】:2013-08-24 07:00:37
【问题描述】:

我需要一个在所有浏览器中看起来几乎相同的 FileUpload,即也在 chrome 中显示文件输入字段。所以我正在使用自定义 FileUpload 使用此代码..

CSS

    <style type="text/css">



        #FileUpload {
    position:relative;
            top: -4px;
            left: 0px;
        }

#BrowserVisible {
    position: absolute;
    top: -15px;
    left: 0px;
    z-index: 1;
    background:url(upload.gif) 100% 0px no-repeat;
    height:26px;
    width:240px;
}

#FileField {
    width:155px;
    height:22px;
    margin-right:85px;
    border:solid 1px #000;
    font-size:16px;
}

#BrowserHidden {
    position:relative;
    width:240px;
    height:26px;
    text-align: right;
    -moz-opacity:0;
    filter:alpha(opacity: 0);
    opacity: 0;
    z-index: 2;
}

    </style>

Javascript

<script src="zoom/jquery-1.10.2.min.js"></script>
<script type="text/javascript">
    $('.custom-upload input[type=file]').change(function () {
        $(this).next().find('input').val($(this).val());
    });

</script>

HTML

<div id="FileUpload">
    <input type="file" size="24" id="BrowserHidden" runat="server" onchange="getElementById('FileField').value = getElementById('BrowserHidden').value;" />
    <div id="BrowserVisible"><input type="text" id="FileField" runat="server" /></div>

    <asp:Button ID="Button1" runat="server" OnClick="Button1_Click" Text="Button" style="height: 26px" />
</div>

使用 asp.net 服务器控制就像

Stream fs = file_upload.PostedFile.InputStream;
                BinaryReader br = new BinaryReader(fs);
                Byte[] bytes = br.ReadBytes((Int32)fs.Length);

【问题讨论】:

    标签: c# javascript html asp.net css


    【解决方案1】:

    假设你的标记是这样的:

    <input type="file" id="file1" />
    <br />
    <input type="file" id="file2" />
    

    在您的代码隐藏事件处理程序中,您可以像这样获取文件:

    HttpPostedFile file = Request.Files["file1"]; // Gets contents passed in file1 element
    HttpPostedFile file2 = Request.Files["file2"]; // Gets contents passed in file2 element
    Stream uploadFileStream = file.InputStream;
    // TODO:  Add code to read the streams
    

    【讨论】:

    • 这相当于Stream fs = file_upload.PostedFile.InputStream;
    • 使用这种方法你只需要使用 Stream fs = file.InputStream;
    • 如果我有多个这样的自定义控件怎么办?在 asp.net FileUpload 中,我可以通过Stream fs = file_upload1.PostedFile.InputStream; 指定我想要简单的文件流
    • Request.Files 是发布到服务器的所有文件的集合。此集合允许您通过接受文件上传输入的 id 的索引器访问特定成员。在您提供的示例中,您的输入元素被命名为“BrowserHidden”。如果您有另一个名为“AnotherFile”的文件上传输入,那么您将通过 Request.Files["AnotherFile"] 获取该文件
    • 仅供参考,更新了代码以演示您如何读取多个文件
    猜你喜欢
    • 2012-06-03
    • 2014-02-14
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2017-03-23
    • 1970-01-01
    • 1970-01-01
    • 2011-01-30
    相关资源
    最近更新 更多