使用"<input type ="file".... />"而不是asp:FileUpload

kma*_*ks2 7 html c# asp.net file-upload

我正在修改现有的ASP.NET项目.原作者错误地尝试通过将其可见性设置为隐藏并仅创建两个自定义样式的浏览和保存按钮来创建样式化的asp:FileUpload.

出于安全原因,IE不允许这样做.我的策略是尝试使用type ="file"的输入标签,就像这个例子一样.因此,如果我设置输入,<input type="file" ID="inputFile" /> 如何在我的代码中访问/保存文件,inputFile.SaveAs("someFile.txt");?另外(在后面的代码中)我可以做类似的事情inputFile.HasFile还是有其他类似的东西?

根据建议,我正在尝试以下内容:

             <td>
                Enabled: <asp:CheckBox ID="CheckBox2" runat="server" />    &nbsp;&nbsp;
                <div id="testFileUploader">>
                   <input type="file" id="browserHidden" runat="server" />
                   <div id="browserVisible"><input type="text" id="fileField" /></div>
                </div>
             </td>
Run Code Online (Sandbox Code Playgroud)

Sec*_*ret 14

所以,你可以基于对未来的上传一个随机文件名,则GUIDCodeBehindASPX页面:

HttpPostedFile filePosted = Request.Files["uploadFieldNameFromHTML"];

if (filePosted != null && filePosted.ContentLength > 0)
{
    string fileNameApplication = System.IO.Path.GetFileName(filePosted.FileName);
    string fileExtensionApplication = System.IO.Path.GetExtension(fileNameApplication);

    // generating a random guid for a new file at server for the uploaded file
    string newFile = Guid.NewGuid().ToString() + fileExtensionApplication;
    // getting a valid server path to save
    string filePath = System.IO.Path.Combine(Server.MapPath("uploads"), newFile);

    if (fileNameApplication != String.Empty)
    {
        filePosted.SaveAs(filePath);
    }
}
Run Code Online (Sandbox Code Playgroud)

Request.Files["uploadFieldNameFromHTML"]在此处设置HTML代码中的ID:

<input type='file' id='...' />
Run Code Online (Sandbox Code Playgroud)

另外,不要忘记runat="server"在ASPX页面的主窗体中定义,最好将它设置在主窗体上,不要忘记enctype="multipart/form-data"参数<form>:

<body>
    <form enctype="multipart/form-data" id="form1" runat="server">
        <input type='file' id='uploadFieldNameFromHTML' />
...
Run Code Online (Sandbox Code Playgroud)


mel*_*cia 3

将 runat="server" 添加到对象。这样,它将像任何 asp:FileUpload 控件一样在 CodeBehid 上工作。