gpt4 book ai didi

javascript - 使用 Image URI 将图像文件存储在服务器文件系统中

转载 作者:行者123 更新时间:2023-11-28 05:07:22 26 4
gpt4 key购买 nike

我从这个 Cordova 相机 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;
}

最佳答案

通常我这样做:

后端:

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

关于javascript - 使用 Image URI 将图像文件存储在服务器文件系统中,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/41632568/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com