'Web API, Uploading Image With Caption - Error 415

I've been trying to upload a file, with an extra input for its title/description but i keep getting error 415

my view:

 <form id="upload" enctype="multipart/form-data">
            <div class="form-group">
                <label>Label</label>
                <input type="text" class="form-control" name="label" id="label" />
            </div>
            <div class="form-group">
                <label for="file" class="pb-4">Select File</label>
                <input type="file" class="form-control" id="files" name="files" required>
            </div>
            <div class="form-group">
                <button type="submit" class="btn btn-primary">Upload</button>
            </div>
        </form>

my ajax:

@section scripts {
<script>
    $(document).ready(function () {
        // send multiple files array upload
        $('#upload').submit(function (e) {
            e.preventDefault();
            //multiple file upload 
            var formData = new FormData(this);
            $.ajax({
                url: '/api/v1/file/postfile',
                type: 'POST',
                data: formData,
                async: false,
                success: function (data) {
                    alert(data);
                },
                cache: false,
                contentType: 'application/json',
                processData: false
            });
        });
    });
</script>

}

my api controller:

[HttpPost]
    [Route("api/v1/file/postfile")]
    public async Task<IHttpActionResult> PostFormData(FilesModel filesModel)
    {
        // Check if the request contains multipart/form-data.
        if (!Request.Content.IsMimeMultipartContent())
        {
            throw new HttpResponseException(HttpStatusCode.UnsupportedMediaType);
        }

        string root = HttpContext.Current.Server.MapPath("~/UploadedFiles/");
        var provider = new MultipartFormDataStreamProvider(root);

        try
        {
            // Read the form data.
            await Request.Content.ReadAsMultipartAsync(provider);

            // This illustrates how to get the file names.
            foreach (MultipartFileData file in provider.FileData)
            {
                Trace.WriteLine(file.Headers.ContentDisposition.FileName);
                Trace.WriteLine("Server file path: " + file.LocalFileName);
            }
            var httpRequest = HttpContext.Current.Request;
            if (httpRequest.Files.Count > 0)
            {
                foreach (string file in httpRequest.Files)
                {
                    var postedFile = httpRequest.Files[file];
                    var filePath = HttpContext.Current.Server.MapPath("~/UploadedFiles/" + postedFile.FileName);
                    postedFile.SaveAs(filePath);

                    FilesModel fileUpload = new FilesModel()
                    {

                        Name = postedFile.FileName,
                        DocumentPath = "~/UploadedFiles/" + postedFile.FileName,
                        Label = filesModel.Label
                    };
                    var hack = fileUpload.Label;
                    // Name = postedFile.FileName,
                    // Label = kab
                    // DocumentPath = "~/UploadedFiles/" + postedFile.FileName 

                    ctx.FilesModels.Add(fileUpload);
                    ctx.SaveChanges();
                }
            }

            return Ok();
        }
        catch (System.Exception e)
        {
            return BadRequest();
        }
    }

my model:

public class FilesModel
{
    public int Id { get; set; }
    public string Label { get; set; }
    public string Name { get; set; }
    public string DocumentPath { get; set; }
}

if i remove the FilesModel filesModel as parameter, my api saves the image and the file path, but i really wanted to define a caption/title for the image that's why i attempted to put FilesModel filesModel in the parameter and that's when error 415 occurs.... I really hope you can help , been working for this for a week....

things i tried:

  • added config in web api to support multipart/form-data
  • specified content type on ajax...


Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source