MR.ABC
MR.ABC

Reputation: 4862

How to avoid url encoding in Form Data

I try to post formData while uploading a file from AngularJS to WebApi. For some reason all values are encoded as %5B%5D the keys are normal. I`m using a Library to upload files. Is it a Javscript problem or WebApi. Any idea?

uploadFile: function(ids, files, success, progress, error) {
    return $upload.upload({
        url:  '/Api/User/UploadFile',
        method: "POST",
        data: { ids: ids },
        file: files
    }).progress(progress).success(success).error(error);
}


    public async static Task<MultipartContent> GetMulipartContent(ApiController controller)
    {
        if (!controller.Request.Content.IsMimeMultipartContent())
        {
            throw new HttpResponseException(HttpStatusCode.UnsupportedMediaType);
        }

        var root = HttpContext.Current.Server.MapPath("~/App_Data");
        var provider = new MultipartFormDataStreamProvider(root);
        var fileData = new List<KeyValuePair<string, byte[]>>();

        await controller.Request.Content.ReadAsMultipartAsync(provider);
        foreach (var file in provider.FileData)
        {
            fileData.Add(new KeyValuePair<string, byte[]>(
                file.Headers.ContentDisposition.FileName, 
                File.ReadAllBytes(file.LocalFileName)));           
            FileHelper.WaitFileUnlockedAsync(() => File.Delete(file.LocalFileName), file.LocalFileName, 30, 800);
        }

        return new MultipartContent(provider.FormData, fileData);
    }
}

public class MultipartContent 
{
    public MultipartContent(NameValueCollection formData, List<KeyValuePair<string, byte[]>> fileData)
    {
        FormData = formData;
        FileData = fileData;
    }

    public NameValueCollection FormData { get; private set; }
    public List<KeyValuePair<string, byte[]>> FileData { get; private set; }
}

Upvotes: 4

Views: 118

Answers (2)

MR.ABC
MR.ABC

Reputation: 4862

$upload is a AngularJS Library. The problem was that the upload function only takes directly an array or object and do not allow nested objects. The Problem is solved. Thanks for support.

uploadFile: function(ids, files, success, progress, error) {
    return $upload.upload({
        url:  '/Api/User/UploadFile',
        method: "POST",
        data: ids, //-------- Problem solved.
        file: files
    }).progress(progress).success(success).error(error);
}

Upvotes: 1

BrettJ
BrettJ

Reputation: 980

I would try setting the dataType and the enctype on the AJAX call (not sure what the .upload() method is but it looks like a jQuery AJAX call).

dataType: 'json',
enctype: 'multipart/form-data'

and see if that fixes it.

After further reading, .upload() looks like something special attached to $http service and probably already sets these values.

Upvotes: 1

Related Questions