Custom validation of HttpPostedFileBase

467 views Asked by At

I use MVC5. I've got some issue with file uploading using HttpPostedFileBase. I've got a form where I can can choose a file from my disk and type some information about it(in textbox). When I submit a form the controller action is called. In this action I open file and check if it has some specific data(related with data from textbox). So I do some validation here. I can't do it using JQuery - it's complex. The server side validation is the only option. Finally if validation fails I return model(with file) to the view but after that I've got validation error next to file field but file field is empty. I've read that's hard to return file to the view. I don't want to use ajax to upload file. I want to do it simple. If you got an article that can help, please share it with me.

How can I solve my problem?

1

There are 1 answers

0
Ashley Lee On

I know you mentioned not using AJAX to do file upload, but I think this solution is a very simple one.

Using the following jQuery plugin (https://blueimp.github.io/jQuery-File-Upload/), you can automate that process and if there are any validation issues in your file, then you can return the following model with the error.

string errors = "Errors returned from complex logic";
if (!String.IsNullOrEmpty(errors))
{
    // error response
    status = new ViewDataUploadFilesResult()
    {
        name = Path.GetFileName(hpf.FileName),
        size = hpf.ContentLength,
        error = errors
    };
}

Here is the class needed for the response that matches the jQuery file upload documentation: https://github.com/blueimp/jQuery-File-Upload/wiki/Setup

public class ViewDataUploadFilesResult
{
    public string name { get; set; }
    public int size { get; set; }
    public string type { get; set; }
    public string url { get; set; }
    public string error { get; set; }
}

If I'm understanding correctly, since the file is already on the users computer, you only need to associate the file to the current file they're attempting to upload to returns errors. And to make it so they don't have to reselect the file to upload. I don't see any other reason to need to return the actual file to the user as they already have the file they're uploading.