2012-12-19 1 views
3

Ce que je veux faire est simplement de télécharger une photo sur un webservice en utilisant mono touch/mono droid et mvvmcross, je l'espère d'une manière que je n'ai qu'à écrire le code une fois pour android et IOS :)télécharger une photo vers un service web avec mvvmcross et mono touch

Mon idée initiale est de laisser l'utilisateur choisir une image (dans Android en utilisant une intention) obtenir le chemin pour l'image. Ensuite, utilisez MvxResourceLoader resourceLoader pour ouvrir un flux à partir du chemin, puis utilisez restsharp pour créer une requête de publication avec le flux.

Cependant, je frappe déjà un mur, lorsque l'utilisateur choisit une image, le chemin est par ex. "/ external/images/media/13". ce chemin entraîne une exception fichier introuvable lors de l'utilisation du chargeur de ressources MvxResourceLoader.

Des idées sur les raisons pour lesquelles je reçois l'exception ou existe-t-il un meilleur moyen d'atteindre mon objectif?

Répondre

3

Voilà comment je fini par doinging - vous et merci stuart tous les liens :)

public class PhotoService :IPhotoService, IMvxServiceConsumer<IMvxPictureChooserTask>,IMvxServiceConsumer<IAppSettings> 
    { 
     private const int MaxPixelDimension = 300; 
     private const int DefaultJpegQuality = 64; 

     public void ChoosePhotoForEventItem(string EventGalleryId, string ItemId) 
     { 
     this.GetService<IMvxPictureChooserTask>().ChoosePictureFromLibrary(
       MaxPixelDimension, 
       DefaultJpegQuality, 
       delegate(Stream stream) { UploadImage(stream,EventGalleryId,ItemId); }, 
       () => { /* cancel is ignored */ }); 

     } 

     private void UploadImage(Stream stream, string EventGalleryId, string ItemId) 
     { 
      var settings = this.GetService<IAppSettings>(); 
      string url = string.Format("{0}/EventGallery/image/{1}/{2}", settings.ServiceUrl, EventGalleryId, ItemId); 
      var uploadImageController = new UploadImageController(url); 

      uploadImageController.OnPhotoAvailableFromWebservice +=PhotoAvailableFromWebservice; 

      uploadImageController.UploadImage(stream,ItemId); 

     } 
    } 

    public class PhotoStreamEventArgs : EventArgs 
    { 
     public Stream PictureStream { get; set; } 

     public Action<string> OnSucessGettingPhotoFileName { get; set; } 

     public string URL { get; set; } 
    } 

    public class UploadImageController : BaseController, IMvxServiceConsumer<IMvxResourceLoader>, IMvxServiceConsumer<IErrorReporter>, IMvxServiceConsumer<IMvxSimpleFileStoreService> 
    { 

     public UploadImageController(string uri) 
      : base(uri) 
     { 

     } 
     public event EventHandler<PhotoStreamEventArgs> OnPhotoAvailableFromWebservice; 


     public void UploadImage(Stream stream, string name) 
     { 
      UploadImageStream(stream, name); 
     } 


     private void UploadImageStream(Stream obj, string name) 
     { 

      var request = new RestRequest(base.Uri, Method.POST); 

      request.AddFile("photo", ReadToEnd(obj), name + ".jpg", "image/pjpeg"); 

      //calling server with restClient 
      var restClient = new RestClient(); 

      try 
      { 

       this.ReportError("Billedet overføres", ErrorEventType.Warning); 

       restClient.ExecuteAsync(request, (response) => 
       { 
        if (response.StatusCode == HttpStatusCode.OK) 
        { 
         //upload successfull 
         this.ReportError("Billedet blev overført", ErrorEventType.Warning); 
         if (OnPhotoAvailableFromWebservice != null) 
         { 
          this.OnPhotoAvailableFromWebservice(this, new PhotoStreamEventArgs() { URL = base.Uri }); 
         } 
        } 
        else 
        { 
         //error ocured during upload 
         this.ReportError("Billedet kunne ikke overføres \n" + response.StatusDescription, ErrorEventType.Warning); 
        } 
       }); 
      } 
      catch (Exception e) 
      { 

       this.ReportError("Upload completed succesfully...", ErrorEventType.Warning); 
       if (OnPhotoAvailableFromWebservice != null) 
       { 
        this.OnPhotoAvailableFromWebservice(this, new PhotoStreamEventArgs() { URL = url }); 
       } 
      } 


     } 

     //method for converting stream to byte[] 

     public byte[] ReadToEnd(System.IO.Stream stream) 
     { 
      long originalPosition = stream.Position; 
      stream.Position = 0; 
      try 
      { 
       byte[] readBuffer = new byte[4096]; 
       int totalBytesRead = 0; 
       int bytesRead; 
       while ((bytesRead = stream.Read(readBuffer, totalBytesRead, readBuffer.Length - totalBytesRead)) > 0) 
       { 
        totalBytesRead += bytesRead; 
        if (totalBytesRead == readBuffer.Length) 
        { 

         int nextByte = stream.ReadByte(); 
         if (nextByte != -1) 
         { 
          byte[] temp = new byte[readBuffer.Length * 2]; 
          Buffer.BlockCopy(readBuffer, 0, temp, 0, readBuffer.Length); 
          Buffer.SetByte(temp, totalBytesRead, (byte)nextByte); 
          readBuffer = temp; 
          totalBytesRead++; 
         } 

        } 
       } 

       byte[] buffer = readBuffer; 
       if (readBuffer.Length != totalBytesRead) 
       { 
        buffer = new byte[totalBytesRead]; 
        Buffer.BlockCopy(readBuffer, 0, buffer, 0, totalBytesRead); 
       } 
       return buffer; 
      } 
      finally 
      { 
       stream.Position = originalPosition; 
      } 
     } 

    } 
+0

Est-ce que cela utilise RestSharp? – iwayneo

Questions connexes