在没有jquery或ajax的情况下创建文件上载功能

时间:2014-07-09 02:57:16

标签: c# asp.net file-upload

我必须创建一个只允许.csv文件的文件上传。到目前为止,我有一个化妆品界面:

<asp:Label ID="importLabel" runat="server" Text="Update Prices" CssClass="fieldLabel" />
                <asp:FileUpload ID="importFileUpload" runat="server" OnDataBinding="importFileUpload_DataBinding"/>
                <asp:Button ID="importFileButton" runat="server" Text="Update Prices" CssClass="fieldlabel" OnClick="importFileButton_Click" />
                <br />
                <asp:RegularExpressionValidator ID="uploadValidator" runat="server" ControlToValidate="importFileUpload" ErrorMessage="Only .csv files are allowed" 
                        ValidationExpression="(.+\.([Cc][Ss][Vv]))" />

它应该可以选择.csv文件,但是我不确定我的下一步。任何帮助或任何正确方向的推动都会很棒!

2 个答案:

答案 0 :(得分:1)

下一步是从后面的代码上传所选文件:

    protected void importFileButton_Click(object sender, EventArgs e)
    {
        if (importFileUpload.HasFile)
        {
            string fileExt =
               System.IO.Path.GetExtension(importFileUpload.FileName);

            if (fileExt == ".csv")
            {
                try
                {
                    importFileUpload.SaveAs("C:\\Uploads\\" + importFileUpload.FileName);
                    importLabel.Text = "File name: " +
                        importFileUpload.PostedFile.FileName + "<br>" +
                        importFileUpload.PostedFile.ContentLength + " kb<br>" +
                        "Content type: " +
                        importFileUpload.PostedFile.ContentType;
                }
                catch (Exception ex)
                {
                    importLabel.Text = "ERROR: " + ex.Message.ToString();
                }
            }
            else
                importLabel.Text = "Only .csv files allowed!";
        }
        else
            importLabel.Text = "You have not specified a file.";
    }

答案 1 :(得分:0)

我之前使用过dropzone.js来达到这个目的。它不需要jquery。您应该可以在下面执行以下操作:

Dropzone.options.filedrop = {
acceptedMimeTypes: 'text/csv',
}

有关限制特定mime类型的实现,请参阅this question