如何将图像从图库上传到ios xamarin studio中的web api 2

时间:2017-04-05 19:52:08

标签: c# xamarin xamarin.ios xamarin-studio

我正在使用C#创建一个Native IOS应用程序。我有一个注册表格,我发送带有图像的表格数据。但我无法发送图像,因为我的UIImage控件不包含其路径或名称。我将表单发送到多个部分的web api。文本字段数据正在上传,但图片没有上传。

1 个答案:

答案 0 :(得分:2)

以下是如何从相机/图库中选择图像到UIImageView,然后上传;

使用UIImagePickerController从图库/相机中选择图像

UIImagePickerController galleryImagePicker;
UIImagePickerController cameraImagePicker;

使用以下功能单击按钮或在ImageView上使用弹出按钮在相机/图库之间进行选择:

void ShowSelectPicPopup ()
{
    var actionSheetAlert = UIAlertController.Create ("Select picture",
                                               "Complete action using", UIAlertControllerStyle.ActionSheet);
    actionSheetAlert.AddAction (UIAlertAction.Create ("Camera",
                                      UIAlertActionStyle.Default, (action) => HandleCameraButtonClick ()));
    actionSheetAlert.AddAction (UIAlertAction.Create ("Gallery",
                                      UIAlertActionStyle.Default, (action) => HandleGalleryButtonClick ()));
    actionSheetAlert.AddAction (UIAlertAction.Create ("Cancel", UIAlertActionStyle.Cancel,
                                      (action) => Console.WriteLine ("Cancel button pressed.")));
    // Required for iPad - You must specify a source for the Action Sheet since it is
    // displayed as a popover
    var presentationPopover = actionSheetAlert.PopoverPresentationController;
    if (presentationPopover != null) {
        presentationPopover.SourceView = View;
        presentationPopover.PermittedArrowDirections = UIPopoverArrowDirection.Up;
    }

    PresentViewController (actionSheetAlert, true, null);
}

现在的行动:

void HandleGalleryButtonClick ()
{
    if (galleryImagePicker == null) {
        galleryImagePicker = new UIImagePickerController ();
        galleryImagePicker.SourceType = UIImagePickerControllerSourceType.PhotoLibrary;
        galleryImagePicker.MediaTypes = UIImagePickerController.AvailableMediaTypes (UIImagePickerControllerSourceType.PhotoLibrary);
        galleryImagePicker.FinishedPickingMedia += Handle_FinishedPickingMedia;
        galleryImagePicker.Canceled += Handle_Canceled;
    }
    PresentViewController (galleryImagePicker, true, () => { });
}

void HandleCameraButtonClick ()
{
    if (cameraImagePicker == null) {
        cameraImagePicker = new UIImagePickerController ();
        cameraImagePicker.PrefersStatusBarHidden ();
        cameraImagePicker.SourceType = UIImagePickerControllerSourceType.Camera;
        cameraImagePicker.FinishedPickingMedia += Handle_FinishedPickingCameraMedia;
        cameraImagePicker.Canceled += Handle_CameraCanceled;
    }
    PresentViewController (cameraImagePicker, true, () => { });
}

void Handle_Canceled (object sender, EventArgs e)
{
    galleryImagePicker.DismissViewController (true, () => { });
}

protected void Handle_FinishedPickingMedia (object sender, UIImagePickerMediaPickedEventArgs e)
{
    // determine what was selected, video or image
    bool isImage = false;
    switch (e.Info [UIImagePickerController.MediaType].ToString ()) {
    case "public.image":
        Console.WriteLine ("Image selected");
        isImage = true;
        break;
    case "public.video":
        Console.WriteLine ("Video selected");
        break;
    }

    // get common info (shared between images and video)
    var referenceURL = e.Info [new NSString ("UIImagePickerControllerReferenceUrl")] as NSUrl;
    if (referenceURL != null)
        Console.WriteLine ("Url:" + referenceURL);

    // if it was an image, get the other image info
    if (isImage) {
        // get the original image
        var originalImage = e.Info [UIImagePickerController.OriginalImage] as UIImage;
        if (originalImage != null) {
                // do something with the image
            Console.WriteLine ("got the original image");
            Picture.Image = originalImage; // Picture is the ImageView
            picAssigned = true;
        }
    } else { // if it's a video
         // get video url
        var mediaURL = e.Info [UIImagePickerController.MediaURL] as NSUrl;
        if (mediaURL != null) {
            Console.WriteLine (mediaURL);
        }
    }
    // dismiss the picker
    galleryImagePicker.DismissViewController (true, () => { });
}

protected void Handle_FinishedPickingCameraMedia (object sender, UIImagePickerMediaPickedEventArgs e)
{
    // determine what was selected, video or image
    bool isImage = false;
    switch (e.Info [UIImagePickerController.MediaType].ToString ()) {
    case "public.image":
        Console.WriteLine ("Image selected");
        isImage = true;
        break;
    case "public.video":
        Console.WriteLine ("Video selected");
        break;
    }

    // get common info (shared between images and video)
    var referenceURL = e.Info [new NSString ("UIImagePickerControllerReferenceUrl")] as NSUrl;
    if (referenceURL != null)
        Console.WriteLine ("Url:" + referenceURL);

    // if it was an image, get the other image info
    if (isImage) {
        // get the original image
        var originalImage = UIHelper.RotateCameraImageToProperOrientation (e.Info [UIImagePickerController.OriginalImage] as UIImage, 320);
        if (originalImage != null) {
            // do something with the image
            Console.WriteLine ("got the original image");
            Picture.Image = originalImage; // display
            picAssigned = true;
        }
    } else { // if it's a video
         // get video url
        var mediaURL = e.Info [UIImagePickerController.MediaURL] as NSUrl;
        if (mediaURL != null) {
            Console.WriteLine (mediaURL);
        }
    }
    // dismiss the picker
    cameraImagePicker.DismissViewController (true, () => { });
}

void Handle_CameraCanceled (object sender, EventArgs e)
{
    cameraImagePicker.DismissViewController (true, () => { });
}

您可能需要在Info.plist中添加以下两个权限才能访问相机/图库

Privacy - Camera Usage Description
Privacy - Photo Library Usage Description

他们都是String,而Value可以是" YourAppName需要访问才能使用你的相机"

最后将图片上传为多部分:

首先将图像转换为字节数组

public static byte[] ConvertImageToByteArray(UIImage Picture) {
    byte [] image = null;
    try {
        using (NSData imageData = Picture.Image.AsJPEG (0.5f)) { // Here you can set compression %, 0 = no compression, 1 = max compression, or  the other way around, I'm not sure
        image = new byte [imageData.Length];
        Marshal.Copy (imageData.Bytes, image, 0, Convert.ToInt32 (imageData.Length));
    } catch (Exception e) {
            Console.WriteLine ("Error @ Picture Byte Conversion: " + e.Message);
    }
    return image;
}

最后发布图片,我使用了modernhttpclient

public async Task PostPicture (byte [] image)
{
    try {
        string url = .....;

        var requestContent = new MultipartFormDataContent ();

        ByteArrayContent content = content = new ByteArrayContent (image);
        content.Headers.ContentType = MediaTypeHeaderValue.Parse ("image/jpeg");
        requestContent.Add (content, "file", "post" + DateTime.Now + ".jpg"); // change file name as per your requirements

        string result = await HttpCall.PostMultiPartContent (url, requestContent, null);


    } catch (Exception ex) {
        System.Diagnostics.Debug.WriteLine (ex.Message);
    }
}

public class HttpCall
{
    public static async Task<string> PostMultiPartContent (string url, MultipartFormDataContent content, Action<int> progressAction) // Here you can pass an handler to keep track of the upload % in your UI, I'm passing null above. (Not keeping track)
    {
        try {
            var request = new HttpRequestMessage (HttpMethod.Post, url);
            var progressContent = new ProgressableStreamContent (content, 4096, (sent, total) => {
                var percentCompletion = (int)(((double)sent / total) * 100);
                System.Diagnostics.Debug.WriteLine ("Completion: " + percentCompletion);
                if (progressAction != null)
                    progressAction (percentCompletion);
            });
            request.Content = progressContent;

            var client = new HttpClient();
            var response = await client.SendAsync (request);
            string result = await response.Content.ReadAsStringAsync ();

            System.Diagnostics.Debug.WriteLine ("PostAsync: " + result);
            return result;
        } catch (Exception e) {
            System.Diagnostics.Debug.WriteLine (e.Message);
            return null;
        }
    }
}