Ricardo Fagmer
Ricardo Fagmer

Reputation: 13

Retrofit + Restful c# Upload Files

I got the files to send by Retrofit with Android using Multiparti however on my server I work with .Net C# to build the Restful Service, then How can i create the restful to receive the files multiparti from Retrofit / Android?

sample:

[RoutePrefix("rest/files")]
public class ReceiveImagesController : ApiController
{
    [AcceptVerbs("POST")]
    [Route("SendFiles")]

    public string sendFiles()
    {
        string retorno = "";
        string path = "C:/temp";

       // byte[] Bytes = new byte[files.Inpu]



        return retorno;
    }
}

Upvotes: 1

Views: 1188

Answers (1)

muratoner
muratoner

Reputation: 2702

My sample code and I use file upload in webapi 2. I think your problem will solve below codes.

sing System;
using System.Linq;
using System.Net.Http;
using System.Threading.Tasks;
using System.Web.Http;

namespace WebMvcTest.Controllers
{
   [System.Web.Http.RoutePrefix("api/test")]
    public class FileUploadController : ApiController
    {

        [System.Web.Http.Route("files")]
        [System.Web.Http.HttpPost]
        [ValidateMimeMultipartContentFilter]
        public async Task<FileResult> UploadSingleFile()
        {
            var streamProvider = new MultipartMemoryStreamProvider();
            await Request.Content.ReadAsMultipartAsync(streamProvider);

            string descriptionResult = string.Empty;
            var description =
                streamProvider.Contents.AsEnumerable()
                    .FirstOrDefault(T => T.Headers.ContentDisposition.Name == "\"description\"");
            if (description != null)
            {
                descriptionResult = await description.ReadAsStringAsync();
            }

            return new FileResult
            {
                FileNames = streamProvider.Contents.AsEnumerable().Select(T => T.Headers.ContentDisposition.FileName).ToArray(),
                Names = streamProvider.Contents.AsEnumerable().Select(T => T.Headers.ContentDisposition.FileName).ToArray(),
                ContentTypes = streamProvider.Contents.AsEnumerable().Where(T => T.Headers.ContentType != null).Select(T => T.Headers.ContentType.MediaType).ToArray(),
                Description = descriptionResult,
                CreatedTimestamp = DateTime.UtcNow,
                UpdatedTimestamp = DateTime.UtcNow,
            };
        }
    }
}

Upvotes: 2

Related Questions