我从这个Cordova Camera API获取URL,我发布到WEBAPI。我尝试使用base64,但是当我将它发布到服务器中时,它会增加图像大小。
请在下面找到我的代码并建议我如何将文件保存到服务器。
//WEB API//
public IHttpActionResult UpdateUserDetails(ImageModel model)
{
try
{
if (model.ImageBase64 != "")
{
var PicDataUrl = "";
string ftpurl = "ftp://xxx.xxxxx.xxxx/";
var username = "xxx";
var password = "xxxxx";
string UploadDirectory = "xxxx/xx";
string FileName =model.ImageFileName;
String uploadUrl = String.Format("{0}{1}/{2}", ftpurl, UploadDirectory,FileName);
FtpWebRequest req = (FtpWebRequest)FtpWebRequest.Create(uploadUrl);
req.Proxy = null;
req.Method = WebRequestMethods.Ftp.UploadFile;
req.Credentials = new NetworkCredential(username, password);
req.EnableSsl = false;
req.UseBinary = true;
req.UsePassive = true;
// I am getting URI path like below and need to save this file in server
model.ImageBase64 = C:\Program Files (x86)\IIS Express\services5.jpg
byte[] data =Convert.FromBase64String(model.ImageBase64);
req.ContentLength = data.Length;
Stream stream = req.GetRequestStream();
stream.Write(data, 0, data.Length);
stream.Close();
}
}
}
// I am getting URL from this Cordova Camera API and I am posting to WEBAPI
function onSuccessEdituserProfileGallery(imageData) {
console.log(imageData);
var smallImage
smallImage = document.getElementById('EdituserProfileImage');
smallImage.src = imageData;
customerImgData =smallImage.src;
return customerImgData;
}
答案 0 :(得分:0)
后端:
[HttpPost]
[Route("Upload/Image")]
public async Task<IHttpActionResult> UploadImg()
{
try
{
#region VAR
if (!Directory.Exists(HttpContext.Current.Server.MapPath(string.Concat("~", Constant.Application.User_Cropped_Image_Directory)))) ;
Directory.CreateDirectory(HttpContext.Current.Server.MapPath(string.Concat("~", Constant.Application.User_Cropped_Image_Directory)));
string mapPath = HttpContext.Current.Server.MapPath(string.Concat("~", Constant.Application.User_Cropped_Image_Directory));
HttpRequestMessage request = this.Request;
String fileName = "";
#endregion VAR
#region SPLIT
// Get base64 string from POST
var base64String = request.Content.ReadAsStringAsync().Result;
// SPLIT Content from unecessary data
var split = base64String.Split(',');
var strings = split[1].Split('-');
#endregion SPLIT
// Convert Base64 String to byte[]
byte[] imageBytes = Convert.FromBase64String(strings[0]);
MemoryStream ms = new MemoryStream(imageBytes, 0, imageBytes.Length);
// Convert byte[] to Image
ms.Write(imageBytes, 0, imageBytes.Length);
Image image = Image.FromStream(ms, true);
if (!Directory.Exists(String.Concat(mapPath, fileName).ToLowerInvariant()))
Directory.CreateDirectory(String.Concat(mapPath, fileName).ToLowerInvariant());
fileName = GenericUtils.GetFileNameWithExt(image).ToLowerInvariant();
//name = String.Concat("croppedImage_", fileName);
image.Save(String.Concat(mapPath, fileName).ToLowerInvariant());
return Ok(new { data = String.Concat(Constant.Application.User_Cropped_Image_Directory, fileName).ToLowerInvariant() } );
}
catch (Exception ex)
{
_logger.LogException(ex);
return null;
}
}
Ionic(js):
$scope.takeFromCamera = function () {
document.addEventListener("deviceready", function () {
var options = {
quality: 90,
destinationType: Camera.DestinationType.DATA_URL,
sourceType: Camera.PictureSourceType.CAMERA,
allowEdit: true,
correctOrientation: true,
encodingType: Camera.EncodingType.JPEG,
targetWidth: 600,
targetHeight: 600,
popoverOptions: CameraPopoverOptions,
saveToPhotoAlbum: true
};
if ($cordovaCamera)
$cordovaCamera.getPicture(options).then(function (imageData) {
$scope.imgURI = "data:image/jpeg;base64," + imageData;
//Image in Base64 to send to server for web profile
// var imgRaw = "data:image/jpeg;base64," + imageData;
$upload.upload({
url: enviroment.apiUrl + 'api/Upload/Image',
fields: { 'base64String': $scope.imgURI },
file: $scope.imgURI
}).success(function (data, status, headers, config) {
$scope.imageName = data.data;
$rootScope.$broadcast("update-img", { img: $scope.imageName });
});
}, function () {
$cordovaToast.show('Camera non Disponibile Si Prega di Riprovare piu tardi!', 'long', 'center');
});
}, false);
};