Al Woods
Al Woods

Reputation: 113

Creating a file upload feature without jquery or ajax

I have to create a file upload that only allows .csv files. So far, I have a cosmetic interface of:

<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]))" />

It works as it should where you can select a .csv file, however I'm not sure of my next step here. Any help or any nudge in the right direction would be awesome!

Upvotes: 0

Views: 182

Answers (2)

etr
etr

Reputation: 1262

I have used dropzone.js before for this specific purpose. It does not require jquery. You should be able to do something like this below:

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

See this question on implementation for limiting specific mime types.

Upvotes: 0

Ali
Ali

Reputation: 2592

The next step is uploading the selected file from the code behind:

    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.";
    }

Upvotes: 1

Related Questions