2013-10-06 4 views
2

Я следую this учебник по загрузке файлов на сервер из Android, но я не могу получить код на стороне сервера. Может кто-нибудь, пожалуйста, помогите мне закодировать метод Web Api post, который будет работать с этим андроидным java-загрузчиком? Мой текущий веб апи класс контроллер выглядит следующим образом:Как код MVC Web Api Post метод для загрузки файлов

using System; 
using System.Collections.Generic; 
using System.IO; 
using System.Linq; 
using System.Net; 
using System.Net.Http; 
using System.Threading.Tasks; 
using System.Web; 
using System.Web.Http; 

namespace WSISWebService.Controllers 
{ 
    public class FilesController : ApiController 
    { 
     // GET api/files 
     public IEnumerable<string> Get() 
     { 
      return new string[] { "value1", "value2" }; 
     } 

     // GET api/files/5 
     public string Get(int id) 
     { 
      return "value"; 
     } 

     // POST api/files 
     public string Post([FromBody]string value) 
     { 
      var task = this.Request.Content.ReadAsStreamAsync(); 
      task.Wait(); 
      Stream requestStream = task.Result; 

      try 
      { 
       Stream fileStream = File.Create(HttpContext.Current.Server.MapPath("~/" + value)); 
       requestStream.CopyTo(fileStream); 
       fileStream.Close(); 
       requestStream.Close(); 
      } 
      catch (IOException) 
      { 
       // throw new HttpResponseException("A generic error occured. Please try again later.", HttpStatusCode.InternalServerError); 
      } 

      HttpResponseMessage response = new HttpResponseMessage(); 
      response.StatusCode = HttpStatusCode.Created; 
      return response.ToString(); 
     }   

     // PUT api/files/5 
     public void Put(int id, [FromBody]string value) 
     { 
     } 

     // DELETE api/files/5 
     public void Delete(int id) 
     { 
     } 
    } 
} 

Я довольно отчаянный, чтобы получить эту работу, как крайний срок вторник. Если бы кто-нибудь мог помочь, это было бы высоко оценено.

ответ

5

вы можете отправить файлы в виде многотомных/form-данных

// POST api/files 
    public async Task<HttpResponseMessage> Post() 
    { 
     // Check if the request contains multipart/form-data. 
     if (!Request.Content.IsMimeMultipartContent()) 
     { 
      throw new HttpResponseException(HttpStatusCode.UnsupportedMediaType); 
     } 

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

     string value; 

     try 
     { 
      // Read the form data and return an async data. 
      var result = await Request.Content.ReadAsMultipartAsync(provider); 

      // This illustrates how to get the form data. 
      foreach (var key in provider.FormData.AllKeys) 
      { 
       foreach (var val in provider.FormData.GetValues(key)) 
       { 
        // return multiple value from FormData 
        if (key == "value") 
         value = val; 
       } 
      }      

      if (result.FileData.Any()) 
      {      
       // This illustrates how to get the file names for uploaded files. 
       foreach (var file in result.FileData) 
       { 
        FileInfo fileInfo = new FileInfo(file.LocalFileName); 
        if (fileInfo.Exists) 
        { 
         //do somthing with file 
        } 
       } 
      } 


      HttpResponseMessage response = Request.CreateResponse(HttpStatusCode.Created, value); 
      response.Headers.Location = new Uri(Url.Link("DefaultApi", new { id = files.Id })); 
      return response; 
     } 
     catch (System.Exception e) 
     { 
      return Request.CreateErrorResponse(HttpStatusCode.InternalServerError, e); 
     } 
    } 
Смежные вопросы