1

I would like to create a WebAPI endpoint which accepts an object that contains a property for documents that can be attached. This endpoint should cater for JSON and XML requests, and not sure how to get this working. I have looked around but cannot find a good example to the spec I am looking for. Please see below the type of solution I need assist with please:

Model Objects:

public class User
{
    public User(){
        Documents = new List<Document>();
    }
    public int UserId {get;set;}
    public string FirstName {get;set;}
    public string LastName {get;set;}
    public string Employee {get;set;}
    public List<Document> Documents {get;set;} //e.g. Identity Document, Certifications etc
}
public class Document{
    public int DocumentId {get;set;}
    public string Name {get;set;}
    public string Extension {get;set;}
    public byte[] Data {get;set;}
}

WebAPI Controller EndPoint:

[HttpPost]
public IHttpActionResult(User user){
   ... WHAT TYPE OF CODE DO I NEED HERE ...
}

The main question is how does a client also post to this endpoint, if please you can provide me with an example? Is my model object correct? How can data be posted from the client side using an xml request since the byte array data is not compatible xml?

Donald N. Mafa
  • 5,131
  • 10
  • 39
  • 56

1 Answers1

1

This is backend code(WebApi controller).

    [HttpPost]
    public IHttpActionResult AcceptUserInfoAndFiles()
    {
        User userInfo = new User();
        var httpContext = HttpContext.Current;
        NameValueCollection nvc = HttpContext.Current.Request.Form;

        // Fill User data ....
        userInfo.UserId=Convert.ToInt32(nvc["UserId"]);
        userInfo.FirstName = nvc["FirstName"];

        List<Document> documents = new List<Document>();
        // Check for any uploaded file  
        if (httpContext.Request.Files.Count > 0)
        {
            //Loop through uploaded files                  
            for (int i = 0; i < httpContext.Request.Files.Count; i++)
            {
                HttpPostedFile httpPostedFile = httpContext.Request.Files[i];
                if (httpPostedFile != null)
                {
                    // Get data in byte array
                    byte[] fileData = null;
                    using (var binaryReader = new BinaryReader(httpPostedFile.InputStream))
                    {
                        fileData = binaryReader.ReadBytes(httpPostedFile.ContentLength);
                    }
                    documents.Add(new Document
                    {
                        DocumentId = 1, //Generate your document id
                        Name = httpPostedFile.FileName, // Remove extension if you want to store only name
                        Extension = System.IO.Path.GetExtension(httpPostedFile.FileName), // Get file extension
                        Data = fileData
                    });

                }
            }
        }
        userInfo.Documents = documents;

        return Ok();
    }

Here is front end sample code in jquery and html

    <div>
    <form method="post" action="http://localhost:59462/Api/Values" enctype="multipart/form-data" id="formUpload">
        <div>
            <label for="files">Files</label>
            <input type="file" id="files" name="files" multiple="multiple" />
        </div>
        <button type="button" id="buttonUpload">Upload files</button>
    </form>
</div>
<script>
$(document).ready(function () {

    $('#buttonUpload').on('click', function () {
        var model = new FormData();
        // Get User properties.
        model.append('UserId', 1); // Get from UI
        model.append('FirstName', "Sam"); // Get from UI
        var files = $("#files").get(0).files;

        // Add the uploaded file to the form data collection
        if (files.length > 0) {
            for (f = 0; f < files.length; f++) {
                model.append("UploadedImage", files[f]);
            }
        }

        // Ajax upload
        $.ajax({
            type: "POST",
            url: $("#formUpload").attr("action"),
            contentType: false,
            processData: false,
            data: model
        });
    });
});
</script>

Here are reference links: https://dejanstojanovic.net/aspnet/2018/february/multiple-file-upload-with-aspnet-webapi/ Post JSON with data AND file to Web Api - jQuery / MVC

Narendra
  • 48
  • 5