FileUpload in angularjs

Issue

I’m using angular-file-upload as found in Here. It was working for what I needed, but now the need has changed, and I’d like to be able to send additional data about (object) along with the file. There isn’t much documentation about it. With what I could see, when I used options directive as attribute and provided the data as object, it’s not listed anywhere in FileUploader. Also, my controller gives me an error when I upload. I added a Model class in Post as argument, which is what causing the controller to break.

    [HttpPost]

    public Task<HttpResponseMessage> PostFile(QAFileAttribute QAFile)
    {
        this.QAFile = QAFile;
        string newLocation = GetCurrentUploadDirectory();

        HttpRequestMessage request = this.Request;
        if(!request.Content.IsMimeMultipartContent())
        {
            throw new HttpResponseException(HttpStatusCode.UnsupportedMediaType);
        }

        string root = UploadLocation; //newLocation;

        var provider = new MultipartFormDataStreamProvider(root);

        var task = request.Content.ReadAsMultipartAsync(provider)
            .ContinueWith<HttpResponseMessage>(o =>
            {
                if (o.IsFaulted || o.IsCanceled)
                {
                    Request.CreateErrorResponse(HttpStatusCode.InternalServerError, o.Exception);
                }

                foreach (MultipartFileData file in provider.FileData)
                {
                    if(String.IsNullOrEmpty(file.Headers.ContentDisposition.FileName))
                    {
                        return Request.CreateResponse(HttpStatusCode.NotAcceptable, "Filename is not acceptable.");
                    }

                    UploadFile(file, QAFile);                        
                }

                return Request.CreateResponse(HttpStatusCode.OK);
            });

        return task;
    }// end Post

So, how can I send the multi-part file along with additional data?

Solution

I figured it out myself. This link helped a lot. Turned out, I didn’t have to do a whole lot to provide additional data. I just needed to provide formData as request body to be processed inside the action; the controller action doesn’t take any parameters. The problem with my code was that (I want to say due to improper documentation of angular-file-upload) I had misunderstood what formData is. Turned out, it’s array of objects. It needed to be like this:

var uploader = new FileUploader({
  url: 'api/upload',
  formData: [{...}]

});

This sent the data to the controller action as request body. From there, I just had to access it as provider.FormData["somename"];

Answered By – user1828605

Answer Checked By – Mildred Charles (AngularFixing Admin)

Leave a Reply

Your email address will not be published.