草庐IT

c# - 如何使用 Alamofire POST 请求将图像作为 Base64String 发送以及如何在 Asp.net MVC4 web Api Controller 中处理请求?

coder 2024-01-12 原文

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 将图像发送到 Web API 是否正确?我得到的响应状态为 404?如何使用 Alamofire 和 swift 将图像发送到 asp.net mvc4 web api 以及如何在 Api Controller 中处理请求?

最佳答案

目前我正在做的是这个...

从ImagePicker中获取Image并将其转换为Base64字符串并将其分配给一个变量以备后用...

注意:我正在压缩我的图像以使其更小并将该代码也放入

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 图像作为字符串

@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 Controller 操作

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

        }

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

关于c# - 如何使用 Alamofire POST 请求将图像作为 Base64String 发送以及如何在 Asp.net MVC4 web Api Controller 中处理请求?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/33952508/

有关c# - 如何使用 Alamofire POST 请求将图像作为 Base64String 发送以及如何在 Asp.net MVC4 web Api Controller 中处理请求?的更多相关文章

  1. ruby - 什么是填充的 Base64 编码字符串以及如何在 ruby​​ 中生成它们? - 2

    我正在使用的第三方API的文档状态:"[O]urAPIonlyacceptspaddedBase64encodedstrings."什么是“填充的Base64编码字符串”以及如何在Ruby中生成它们。下面的代码是我第一次尝试创建转换为Base64的JSON格式数据。xa=Base64.encode64(a.to_json) 最佳答案 他们说的padding其实就是Base64本身的一部分。它是末尾的“=”和“==”。Base64将3个字节的数据包编码为4个编码字符。所以如果你的输入数据有长度n和n%3=1=>"=="末尾用于填充n%

  2. ruby - 如何指定 Rack 处理程序 - 2

    Rackup通过Rack的默认处理程序成功运行任何Rack应用程序。例如:classRackAppdefcall(environment)['200',{'Content-Type'=>'text/html'},["Helloworld"]]endendrunRackApp.new但是当最后一行更改为使用Rack的内置CGI处理程序时,rackup给出“NoMethodErrorat/undefinedmethod`call'fornil:NilClass”:Rack::Handler::CGI.runRackApp.newRack的其他内置处理程序也提出了同样的反对意见。例如Rack

  3. ruby-on-rails - Rails HTML 请求渲染 JSON - 2

    在我的Controller中,我通过以下方式在我的index方法中支持HTML和JSON:respond_todo|format|format.htmlformat.json{renderjson:@user}end在浏览器中拉起它时,它会自然地以HTML呈现。但是,当我对/user资源进行内容类型为application/json的curl调用时(因为它是索引方法),我仍然将HTML作为响应。如何获取JSON作为响应?我还需要说明什么? 最佳答案 您应该将.json附加到请求的url,提供的格式在routes.rb的路径中定义。这

  4. c# - 如何在 ruby​​ 中调用 C# dll? - 2

    如何在ruby​​中调用C#dll? 最佳答案 我能想到几种可能性:为您的DLL编写(或找人编写)一个COM包装器,如果它还没有,则使用Ruby的WIN32OLE库来调用它;看看RubyCLR,其中一位作者是JohnLam,他继续在Microsoft从事IronRuby方面的工作。(估计不会再维护了,可能不支持.Net2.0以上的版本);正如其他地方已经提到的,看看使用IronRuby,如果这是您的技术选择。有一个主题是here.请注意,最后一篇文章实际上来自JohnLam(看起来像是2009年3月),他似乎很自在地断言RubyCL

  5. jquery - 我的 jquery AJAX POST 请求无需发送 Authenticity Token (Rails) - 2

    rails中是否有任何规定允许站点的所有AJAXPOST请求在没有authenticity_token的情况下通过?我有一个调用Controller方法的JqueryPOSTajax调用,但我没有在其中放置任何真实性代码,但调用成功。我的ApplicationController确实有'request_forgery_protection'并且我已经改变了config.action_controller.consider_all_requests_local在我的environments/development.rb中为false我还搜索了我的代码以确保我没有重载ajaxSend来发送

  6. C# 到 Ruby sha1 base64 编码 - 2

    我正在尝试在Ruby中复制Convert.ToBase64String()行为。这是我的C#代码:varsha1=newSHA1CryptoServiceProvider();varpasswordBytes=Encoding.UTF8.GetBytes("password");varpasswordHash=sha1.ComputeHash(passwordBytes);returnConvert.ToBase64String(passwordHash);//returns"W6ph5Mm5Pz8GgiULbPgzG37mj9g="当我在Ruby中尝试同样的事情时,我得到了相同sha

  7. ruby-on-rails - 添加回形针新样式不影响旧上传的图像 - 2

    我有带有Logo图像的公司模型has_attached_file:logo我用他们的Logo创建了许多公司。现在,我需要添加新样式has_attached_file:logo,:styles=>{:small=>"30x15>",:medium=>"155x85>"}我是否应该重新上传所有旧数据以重新生成新样式?我不这么认为……或者有什么rake任务可以重新生成样式吗? 最佳答案 参见Thumbnail-Generation.如果rake任务不适合你,你应该能够在控制台中使用一个片段来调用重新处理!关于相关公司

  8. ruby - 使用 Ruby 通过 Outlook 发送消息的最简单方法是什么? - 2

    我的工作要求我为某些测试自动生成电子邮件。我一直在四处寻找,但未能找到可以快速实现的合理解决方案。它需要在outlook而不是其他邮件服务器中,因为我们有一些奇怪的身份验证规则,我们需要保存草稿而不是仅仅发送邮件的选项。显然win32ole可以做到这一点,但我找不到任何相当简单的例子。 最佳答案 假设存储了Outlook凭据并且您设置为自动登录到Outlook,WIN32OLE可以很好地完成此操作:require'win32ole'outlook=WIN32OLE.new('Outlook.Application')message=

  9. 【鸿蒙应用开发系列】- 获取系统设备信息以及版本API兼容调用方式 - 2

    在应用开发中,有时候我们需要获取系统的设备信息,用于数据上报和行为分析。那在鸿蒙系统中,我们应该怎么去获取设备的系统信息呢,比如说获取手机的系统版本号、手机的制造商、手机型号等数据。1、获取方式这里分为两种情况,一种是设备信息的获取,一种是系统信息的获取。1.1、获取设备信息获取设备信息,鸿蒙的SDK包为我们提供了DeviceInfo类,通过该类的一些静态方法,可以获取设备信息,DeviceInfo类的包路径为:ohos.system.DeviceInfo.具体的方法如下:ModifierandTypeMethodDescriptionstatic StringgetAbiList​()Obt

  10. 基于C#实现简易绘图工具【100010177】 - 2

    C#实现简易绘图工具一.引言实验目的:通过制作窗体应用程序(C#画图软件),熟悉基本的窗体设计过程以及控件设计,事件处理等,熟悉使用C#的winform窗体进行绘图的基本步骤,对于面向对象编程有更加深刻的体会.Tutorial任务设计一个具有基本功能的画图软件**·包括简单的新建文件,保存,重新绘图等功能**·实现一些基本图形的绘制,包括铅笔和基本形状等,学习橡皮工具的创建**·设计一个合理舒适的UI界面**注明:你可能需要先了解一些关于winform窗体应用程序绘图的基本知识,以及关于GDI+类和结构的知识二.实验环境Windows系统下的visualstudio2017C#窗体应用程序三.

随机推荐