簡體   English   中英

如何使用Alamofire POST請求將圖像作為Base64String發送以及如何在Asp.net MVC4 web Api控制器中處理請求?

[英]How to Send Image as Base64String using Alamofire POST request and how to handle the request in Asp.net MVC4 web Api Controller?

在iOS和我的項目中的新手我使用Alamofire(3.0.0)和后端asp.net MVC4 web Api。 我已經通過這種方式將我的圖像轉換為base64string

swift 2.0

var userProfileImage : String = ""
func imagePickerController(picker: UIImagePickerController, didFinishPickingMediaWithInfo info: [String : AnyObject]) {

 if let _image = info["UIImagePickerControllerEditedImage"] as? UIImage
                //if let _image = info["UIImagePickerControllerOriginalImage"] as? UIImage
                {
                    capturedImage = _image

                    self.profilePicture.image = _image
                    //cache.saveImage(capturedImage, path: _cache.fileInDocumentsDirectory("profileImage"))
                    let imagetosave = UIImageJPEGRepresentation(_image, 1.0)
                    let base64encodedImage  = imagetosave!.base64EncodedStringWithOptions(NSDataBase64EncodingOptions(rawValue: 0)) 


userProfileImage = base64encodedImage
}
else if let _image = info["UIImagePickerControllerOriginalImage"] as? UIImage

{
 let __image = UIImageJPEGRepresentation(_image,1.0)
                            let base64encodedImage = __image!.base64EncodedStringWithOptions(NSDataBase64EncodingOptions(rawValue: 0))


 userProfileImage = base64encodedImage
}
    }

我的Alamofire請求如下

let params = ["userid":"\(user)" , "firstname":"\(String(_firstName))" , "middlename":"\(String(_middlename))","lastname":"\(String(_lastname))","email":"\(String(_email))","base64String":"\(userProfileImage)"]
     Alamofire.request(.POST, App.AppHomeURL() + "Update_Profile", parameters : params, encoding : .JSON).responseJSON{
            response in
 case .Success(let data) :
  let json = JSON(data)

                print("JSON DATA  : \(json)")
case .Failure(let error):
print(error)

}

最后我接受請求的ApiController是

[System.Web.Http.HttpPost]
        public JsonResult Update_Profile(string userid, string firstname, string middlename, string lastname, string email, string base64String)
        {
     // code goes here ...
}

是使用Alamofire將圖像發送到網絡API的正確方法我的響應狀態是404嗎? 如何使用Alamofire和swift發送圖像到asp.net mvc4 web api以及如何在Api Controller中處理請求?

目前我在做的是......

從ImagePicker獲取圖像並將其轉換為Base64字符串並將其分配給變量供以后使用...

注意:我正在壓縮我的Image以使其變小並放置該代碼

var userProfileImage : String = ""
func imagePickerController(picker: UIImagePickerController, didFinishPickingMediaWithInfo info: [String : AnyObject]) {
     let capturedImage : UIImage
     if let _image = info["UIImagePickerControllerEditedImage"] as? UIImage
            {
                 capturedImage = _image
                 self.profilePicture.image = _image

                 let _image_compressed = compressImage(_image)
                 let imagetosave = UIImageJPEGRepresentation(_image_compressed , 1.0)
                 let base64encodedImage  = imagetosave!.base64EncodedStringWithOptions(NSDataBase64EncodingOptions.Encoding64CharacterLineLength)
                 userProfileImage =  base64encodedImage
            }
            else if let _image = info["UIImagePickerControllerOriginalImage"] as? UIImage
                         {
                            capturedImage = _image
                            let _imageCompressed = compressImage(_image)
                            let __image = UIImageJPEGRepresentation(_imageCompressed , 1.0)
                            let base64encodedImage = __image!.base64EncodedStringWithOptions(NSDataBase64EncodingOptions(rawValue : 0))
                            userProfileImage =  base64encodedImage
                            self.profilePicture.image = _image
                          }
                            else
                               {
                                   return
                               }
                                 dismissViewControllerAnimated(true, completion: nil)

    }

//壓縮圖像

func compressImage(image : UIImage) -> UIImage
{
    var _actualImageHeight : CGFloat = image.size.height
    var _actualImageWidth : CGFloat = image.size.width
    let _maxHeight : CGFloat = 300.0
    let _maxWidth : CGFloat = 400.0
    var _imageRatio : CGFloat = _actualImageWidth / _actualImageHeight
    let _maxRatio: CGFloat = _maxWidth / _maxHeight
    let _imageCompressionQuality : CGFloat = 0.5 // makes the image get compressed to 50% of its actual size

    if _actualImageHeight > _maxHeight || _actualImageWidth > _maxWidth
    {
        if _imageRatio < _maxRatio
        {
            // Adjust thw width according to the _maxHeight
            _imageRatio = _maxHeight / _actualImageHeight
            _actualImageWidth = _imageRatio * _actualImageWidth
            _actualImageHeight = _maxHeight
        }
        else
        {
            if _imageRatio > _maxRatio
            {
                // Adjust height according to _maxWidth
                _imageRatio = _maxWidth / _actualImageWidth
                _actualImageHeight = _imageRatio * _actualImageHeight
                _actualImageWidth = _maxWidth
            }
            else
            {
                _actualImageHeight = _maxHeight
                _actualImageWidth = _maxWidth
            }

        }
    }
    let _compressedImage : CGRect = CGRectMake(0.0 , 0.0 , _actualImageWidth , _actualImageHeight)
    UIGraphicsBeginImageContext(_compressedImage.size)
    image.drawInRect(_compressedImage)
    let img: UIImage = UIGraphicsGetImageFromCurrentImageContext()
    let imageData: NSData = UIImageJPEGRepresentation(img, _imageCompressionQuality)!
    UIGraphicsEndImageContext()
    return UIImage(data: imageData)!
}

這是我的方法(IBAction),我將用戶配置文件詳細信息發送到包含Base64圖像為String的服務器

@IBAction func saveUserDetails(sender: AnyObject)  {
     let _oldpass = userOldPassword.text!
     let _newPass = userNewPassword.text!
     let _newPassCoonfirm = userRetypedPassword.text!
     let _email : String = userEmail.text!
     var _firstName : String = ""
     let _middlename : String = userMiddleName.text!
     let _lastname : String = userLastName.text!
     let _pass : String = userNewPassword.text!
     var _profileImage : String = ""

          if let profileImage = self.userProfileImage as? String
                 {
                     _profileImage = profileImage
                 }   
                      else
                           {
                             _profileImage = ""
                           }

          if let _first = userFirstName.text! as? String
                {
                     _firstName = _first
                }
                    else
                          {
                            _firstName = ""
                          }

        let params = ["firstname":"\(String(_firstName))"
            ,"middlename":"\(String(_middlename))"
            ,"lastname":"\(String(_lastname))"
            ,"password":"\(String(_pass))"
            ,"email":"\(String(_email))"
            ,"oldpassword":"\(_oldpass)"
            ,"base64String":"\(_profileImage)"]

            Alamofire.request(.POST, App.AppHomeURL() + "Update_Profile", parameters : params , encoding : .JSON).responseJSON{
                  response in
                        switch response.result {
                               case .Success(let data) :
                                    let json = JSON(data)
                                    let ProfileEdit = json["Data"]
                                        if (ProfileEdit) 
                                           {
                                             print("true")
                                           }

                               case .Failure(let _error):
                                       print("false")      
            }
        }
     }

這是我的Asp.Net MVC控制器動作

[route.System.Web.Http.HttpPost]
        [HttpRoute("api/Home/Update_Profile")]
        public JsonResult Update_Profile([FromBody]UpdateProfileViewModel updateprofileviewmodel)
        {
            UserModel usermodelforemail = Helper.FindUserByEmail(updateprofileviewmodel.email);
            System.Web.Mvc.JsonResult usertoreturn = new System.Web.Mvc.JsonResult();
            UserModel usermodel = new UserModel();
            usermodel = FridgeHelper.FindUserByObjectId(updateprofileviewmodel.userid);
            usermodel.FirstName = updateprofileviewmodel.firstname;
            usermodel.MiddleName = updateprofileviewmodel.middlename;
            usermodel.LastName = updateprofileviewmodel.lastname;
            usermodel.Email = updateprofileviewmodel.email;

             //save photo
            if (updateprofileviewmodel.base64String != null)
            {
                byte[] imageBytes = Convert.FromBase64String(updateprofileviewmodel.base64String);
                MemoryStream ms = new MemoryStream(imageBytes, 0,
                  imageBytes.Length);
                // Convert byte[] to Image
                ms.Write(imageBytes, 0, imageBytes.Length);
                Image image = Image.FromStream(ms, true);
                string filenametosave = usermodel._id + "." + System.Drawing.Imaging.ImageFormat.Jpeg;
                var path = System.Web.Hosting.HostingEnvironment.MapPath("~/Content/UserProfilePictures/" + filenametosave);
                if (System.IO.File.Exists(path))
                {
                    System.IO.File.Delete(path);
                }
                image.Save(path);
                usermodel.Photo = filenametosave;
            }

            bool resultvalue = false;
            resultvalue = Helper.UpdateUser(usermodel);

            if (resultvalue)
            {
                usertoreturn.Data = "true";
            }
            else
            {
                usertoreturn.Data = "false";
            }
            return usertoreturn;

        }

現在一切都按我需要的方式工作...... :)

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM