繁体   English   中英

如何在iOS Xamarin Studio中将图像从画廊上传到Web API 2

[英]How to upload image from gallery to web api 2 in ios xamarin studio

我正在使用C#制作本机IOS应用程序。 我有一个注册表格,并且正在发送带有图像的表格数据。 但是我无法发送图像,因为我的UIImage控件不包含其路径或名称。我正在将Form分段发送给Web api。 文本字段数据正在上载,但图像未上载。

您可以按照以下方法将“相机/图库”中的图像拾取到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中添加以下两个权限才能访问Camera / Gallery

Privacy - Camera Usage Description
Privacy - Photo Library Usage Description

它们都是String,Value可能类似于“您的应用名称需要访问权限才能使用您的相机”

最后以多部分的形式上传图像:

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

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;
        }
    }
}

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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