Base-64 字符数组或字符串的长度无效 c# mvc4 web Api
Invalid length for a Base-64 char array or string c# mvc4 web Api
我正在使用 swift 2.0 和 Alamofire 3.0。我向 Alamofire 发出了 POST 请求。我请求中的参数包含文本和 base64 编码图像。但是我收到一条消息作为回复,说 "An error occurred"。 Asp.net mmvc4 web api 用作后端。 base64 字符串似乎太长了。通过使用在线文本编辑器 editpad。因为我发现我的 base64 字符串的字符数是 4405562 个字符(包括空格)
图片转base64码(swift 2)
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 imagetosave = UIImageJPEGRepresentation(_image, 1.0)
let base64encodedImage = imagetosave!.base64EncodedStringWithOptions(NSDataBase64EncodingOptions.Encoding64CharacterLineLength)
userProfileImage = base64encodedImage
}
}
else if let _image = info["UIImagePickerControllerOriginalImage"] as? UIImage
{
capturedImage = _image
var __image = UIImageJPEGRepresentation(_image,1.0)
let base64encodedImage = __image!.base64EncodedStringWithOptions(NSDataBase64EncodingOptions.Encoding64CharacterLineLength)
userProfileImage = base64encodedImage
self.profilePicture.image = _image
}
else
{
return
}
dismissViewControllerAnimated(true, completion: nil)
}
Alamofire POST请求
let params = ["userid":"\(user)" , "firstname":"\(String(_firstName))" , "middlename":"\(String(_middlename))","lastname":"\(String(_lastname))","password":"\(String(_pass))","email":"\(String(_email))","oldpassword":"\(_oldpass)","base64String":"userProfileImage"]
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 _data : String = json["Data"].string!
if (_data == "true")
{
let _storyBoard : UIStoryboard = UIStoryboard(name: "Main", bundle: nil)
let _profile = _storyBoard.instantiateViewControllerWithIdentifier("ProfileViewController") as! ProfileViewController
self.navigationController?.pushViewController(_profile, animated: true)
}
这里我得到 JSON 响应 "Message" :"An error has occurred"
接收POST请求的后端代码
public JsonResult Update_Profile([FromBody]UpdateProfileViewModel updateprofileviewmodel)
{
//code goes here
if (updateprofileviewmodel.base64String != "" && updateprofileviewmodel.base64String != null && 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/FridgeUserProfilePictures/" + filenametosave);
if (System.IO.File.Exists(path))
{
System.IO.File.Delete(path);
}
image.Save(path);
usermodel.Photo = filenametosave;
}
}
此处字节[] imageBytes = Convert.FromBase64String(updateprofileviewmodel.base64String);
发生异常说
'System.FormatException' 类型的异常发生在 mscorlib.dll 但未在用户代码中处理
附加信息:Base-64 字符数组或字符串的长度无效。
编辑:
只需将从 Swift 获取的 Base64 字符串放入 webApi 方法
的变量中
var base64String = "Base64 string got in ios"
this worked and created an image in server.
I tried using POSTMAN a google extension. on using it I found that the actual String is not getting passed. say the string length is 100 on passing only string with length 50 is send and produced the error mentioned in the Question. later I tried this and the response is
response = Optional(<NSHTTPURLResponse: 0x7fe593618b30> { URL: http://app.appurl } { status code: 500, headers {
"Cache-Control" = private;
"Content-Length" = 3420;
"Content-Type" = "text/html; charset=utf-8";
Date = "Tue, 01 Dec 2015 11:59:22 GMT";
Server = "Microsoft-IIS/8.0";
"X-AspNet-Version" = "4.0.30319";
"X-Powered-By" = "ASP.NET";
} })
<html>
<head>
<title>Runtime Error</title>
<meta name="viewport" content="width=device-width" />
<style>
body {
font-family: "Verdana";
font-weight: normal;
font-size: .7em;
color: black;
}
p {
font-family: "Verdana";
font-weight: normal;
color: black;
margin-top: -5px
}
b {
font-family: "Verdana";
font-weight: bold;
color: black;
margin-top: -5px
}
H1 {
font-family: "Verdana";
font-weight: normal;
font-size: 18pt;
color: red
}
H2 {
font-family: "Verdana";
font-weight: normal;
font-size: 14pt;
color: maroon
}
pre {
font-family: "Consolas", "Lucida Console", Monospace;
font-size: 11pt;
margin: 0;
padding: 0.5em;
line-height: 14pt
}
.marker {
font-weight: bold;
color: black;
text-decoration: none;
}
.version {
color: gray;
}
.error {
margin-bottom: 10px;
}
.expandable {
text-decoration: underline;
font-weight: bold;
color: navy;
cursor: hand;
}
@media screen and (max-width: 639px) {
pre {
width: 440px;
overflow: auto;
white-space: pre-wrap;
word-wrap: break-word;
}
}
@media screen and (max-width: 479px) {
pre {
width: 280px;
}
}
</style>
</head>
<body bgcolor="white">
<span><H1>Server Error in '/' Application.<hr width=100% size=1 color=silver></H1>
<h2> <i>Runtime Error</i> </h2></span>
<font face="Arial, Helvetica, Geneva, SunSans-Regular, sans-serif ">
<b> Description: </b>An application error occurred on the server. The current custom error settings for this application prevent the details of the application error from being viewed remotely (for security reasons). It could, however, be viewed by browsers running on the local server machine.
<br><br>
<b>Details:</b> To enable the details of this specific error message to be viewable on remote machines, please create a <customErrors> tag within a "web.config" configuration file located in the root directory of the current web application. This <customErrors> tag should then have its "mode" attribute set to "Off".<br><br>
<table width=100% bgcolor="#ffffcc">
<tr>
<td>
<code><pre>
<!-- Web.Config Configuration File -->
<configuration>
<system.web>
<customErrors mode="Off"/>
</system.web>
</configuration></pre></code>
</td>
</tr>
</table>
<br>
<b>Notes:</b> The current error page you are seeing can be replaced by a custom error page by modifying the "defaultRedirect" attribute of the application's <customErrors> configuration tag to point to a custom error page URL.<br><br>
<table width=100% bgcolor="#ffffcc">
<tr>
<td>
<code><pre>
<!-- Web.Config Configuration File -->
<configuration>
<system.web>
<customErrors mode="RemoteOnly" defaultRedirect="mycustompage.htm"/>
</system.web>
</configuration></pre></code>
</td>
</tr>
</table>
<br>
</body>
</html>
)
可能不是你的答案,但我做到了,
在将图像发送到服务器之前压缩图像,现在一切正常。
我正在使用 swift 2.0 和 Alamofire 3.0。我向 Alamofire 发出了 POST 请求。我请求中的参数包含文本和 base64 编码图像。但是我收到一条消息作为回复,说 "An error occurred"。 Asp.net mmvc4 web api 用作后端。 base64 字符串似乎太长了。通过使用在线文本编辑器 editpad。因为我发现我的 base64 字符串的字符数是 4405562 个字符(包括空格)
图片转base64码(swift 2)
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 imagetosave = UIImageJPEGRepresentation(_image, 1.0)
let base64encodedImage = imagetosave!.base64EncodedStringWithOptions(NSDataBase64EncodingOptions.Encoding64CharacterLineLength)
userProfileImage = base64encodedImage
}
}
else if let _image = info["UIImagePickerControllerOriginalImage"] as? UIImage
{
capturedImage = _image
var __image = UIImageJPEGRepresentation(_image,1.0)
let base64encodedImage = __image!.base64EncodedStringWithOptions(NSDataBase64EncodingOptions.Encoding64CharacterLineLength)
userProfileImage = base64encodedImage
self.profilePicture.image = _image
}
else
{
return
}
dismissViewControllerAnimated(true, completion: nil)
}
Alamofire POST请求
let params = ["userid":"\(user)" , "firstname":"\(String(_firstName))" , "middlename":"\(String(_middlename))","lastname":"\(String(_lastname))","password":"\(String(_pass))","email":"\(String(_email))","oldpassword":"\(_oldpass)","base64String":"userProfileImage"]
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 _data : String = json["Data"].string!
if (_data == "true")
{
let _storyBoard : UIStoryboard = UIStoryboard(name: "Main", bundle: nil)
let _profile = _storyBoard.instantiateViewControllerWithIdentifier("ProfileViewController") as! ProfileViewController
self.navigationController?.pushViewController(_profile, animated: true)
}
这里我得到 JSON 响应 "Message" :"An error has occurred"
接收POST请求的后端代码
public JsonResult Update_Profile([FromBody]UpdateProfileViewModel updateprofileviewmodel)
{
//code goes here
if (updateprofileviewmodel.base64String != "" && updateprofileviewmodel.base64String != null && 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/FridgeUserProfilePictures/" + filenametosave);
if (System.IO.File.Exists(path))
{
System.IO.File.Delete(path);
}
image.Save(path);
usermodel.Photo = filenametosave;
}
}
此处字节[] imageBytes = Convert.FromBase64String(updateprofileviewmodel.base64String);
发生异常说
'System.FormatException' 类型的异常发生在 mscorlib.dll 但未在用户代码中处理 附加信息:Base-64 字符数组或字符串的长度无效。
编辑: 只需将从 Swift 获取的 Base64 字符串放入 webApi 方法
的变量中var base64String = "Base64 string got in ios" this worked and created an image in server. I tried using POSTMAN a google extension. on using it I found that the actual String is not getting passed. say the string length is 100 on passing only string with length 50 is send and produced the error mentioned in the Question. later I tried this and the response is
response = Optional(<NSHTTPURLResponse: 0x7fe593618b30> { URL: http://app.appurl } { status code: 500, headers {
"Cache-Control" = private;
"Content-Length" = 3420;
"Content-Type" = "text/html; charset=utf-8";
Date = "Tue, 01 Dec 2015 11:59:22 GMT";
Server = "Microsoft-IIS/8.0";
"X-AspNet-Version" = "4.0.30319";
"X-Powered-By" = "ASP.NET";
} })
<html>
<head>
<title>Runtime Error</title>
<meta name="viewport" content="width=device-width" />
<style>
body {
font-family: "Verdana";
font-weight: normal;
font-size: .7em;
color: black;
}
p {
font-family: "Verdana";
font-weight: normal;
color: black;
margin-top: -5px
}
b {
font-family: "Verdana";
font-weight: bold;
color: black;
margin-top: -5px
}
H1 {
font-family: "Verdana";
font-weight: normal;
font-size: 18pt;
color: red
}
H2 {
font-family: "Verdana";
font-weight: normal;
font-size: 14pt;
color: maroon
}
pre {
font-family: "Consolas", "Lucida Console", Monospace;
font-size: 11pt;
margin: 0;
padding: 0.5em;
line-height: 14pt
}
.marker {
font-weight: bold;
color: black;
text-decoration: none;
}
.version {
color: gray;
}
.error {
margin-bottom: 10px;
}
.expandable {
text-decoration: underline;
font-weight: bold;
color: navy;
cursor: hand;
}
@media screen and (max-width: 639px) {
pre {
width: 440px;
overflow: auto;
white-space: pre-wrap;
word-wrap: break-word;
}
}
@media screen and (max-width: 479px) {
pre {
width: 280px;
}
}
</style>
</head>
<body bgcolor="white">
<span><H1>Server Error in '/' Application.<hr width=100% size=1 color=silver></H1>
<h2> <i>Runtime Error</i> </h2></span>
<font face="Arial, Helvetica, Geneva, SunSans-Regular, sans-serif ">
<b> Description: </b>An application error occurred on the server. The current custom error settings for this application prevent the details of the application error from being viewed remotely (for security reasons). It could, however, be viewed by browsers running on the local server machine.
<br><br>
<b>Details:</b> To enable the details of this specific error message to be viewable on remote machines, please create a <customErrors> tag within a "web.config" configuration file located in the root directory of the current web application. This <customErrors> tag should then have its "mode" attribute set to "Off".<br><br>
<table width=100% bgcolor="#ffffcc">
<tr>
<td>
<code><pre>
<!-- Web.Config Configuration File -->
<configuration>
<system.web>
<customErrors mode="Off"/>
</system.web>
</configuration></pre></code>
</td>
</tr>
</table>
<br>
<b>Notes:</b> The current error page you are seeing can be replaced by a custom error page by modifying the "defaultRedirect" attribute of the application's <customErrors> configuration tag to point to a custom error page URL.<br><br>
<table width=100% bgcolor="#ffffcc">
<tr>
<td>
<code><pre>
<!-- Web.Config Configuration File -->
<configuration>
<system.web>
<customErrors mode="RemoteOnly" defaultRedirect="mycustompage.htm"/>
</system.web>
</configuration></pre></code>
</td>
</tr>
</table>
<br>
</body>
</html>
)
可能不是你的答案,但我做到了, 在将图像发送到服务器之前压缩图像,现在一切正常。