简体   繁体   中英

How do I receive both json and binary data in a post to my webapi controller?

I have a class I created called Event . My Event class contains a list of Documents . Document is another class I've created. Each Document class contains a class called DocumentData which has a property called FileData of type byte[] .

So it looks like this:

myEventObj.Documents[0].DocumentData.FileData

Right now my controller that accepts new or updated Events only accepts json data, which is fine for everything in my Event class except for FileData .

I have another controller which accepts file uploads. The problem is, there's no easy way for me to link the binary file data accepted by my second controller and pair it with the FileData property of an Event sent to my first controller. How do I combine them so there's only one call to my web service to save both an Event along with any file data?

Here's my Post and Put functions of my Event controller:

[HttpPost]
public IHttpActionResult Post(Event coreEvent) {
    coreEvent.PrepareToPersist();
    _unitOfWork.Events.Add(coreEvent);
    _unitOfWork.Complete();
    return Created("api/events/" + coreEvent.EventId, coreEvent);
}

[HttpPut]
public IHttpActionResult Put(Event coreEvent) {
    coreEvent.PrepareToPersist();
    _unitOfWork.Events.Update(coreEvent);
    _unitOfWork.Complete();
    return Ok(coreEvent);
}

Here's the Post function for my controller that handles file uploads:

[HttpPost]
public async Task<IHttpActionResult> Post() {
    if (!Request.Content.IsMimeMultipartContent()) {
        throw new HttpResponseException(HttpStatusCode.UnsupportedMediaType);
    }

    var provider = new MultipartMemoryStreamProvider();

    try {
        await Request.Content.ReadAsMultipartAsync(provider);

        foreach (var file in provider.Contents) {
            string filename = file.Headers.ContentDisposition.FileName.Trim('\"');
            byte[] buffer = await file.ReadAsByteArrayAsync();
        }
        return Ok();
    }
    catch (System.Exception e) {
        return InternalServerError(e);
    }
}

How do I put these together?

Well usually I prefer it in two methods to support multi ajax upload files, so the second method will support uploading files by Ajax and will return a unique key for the uploaded file, after you saving it somewhere on the server and adding a record for it in the database ( ex: attachments table),

and when you call the first method for posing event , your object myEventObj.Documents[0].DocumentData.FileData will contains the returned key from the second method, so probably your object will be, myEventObj.Documents as List of string (files keys)

Thanks

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM