![](/img/trans.png)
[英]Is it possible to reduce the image size when converting it into base64 format in react js?
[英]Reduce size of image when converted to Base64
我在JavaScript中使用文件閱讀器,我需要將我的圖像發布到WebApi並將其轉換為字節數組並將其保存在服務器中,其工作正常,現在我的問題是base64字符串增加圖像的大小,讓我說如果我上傳30Kb的圖像,它在服務器中存儲有389Kb,如何保存相同尺寸或減小圖像尺寸需要幫助
//File Reader
function OnFileEditImageEntry(file) {
var reader = new FileReader();
reader.onloadend = function (evt) {
var ImageBase64 = evt.target.result;
return ImageBase64 ;
};
reader.readAsDataURL(file);
}
//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;
byte[] data =Convert.FromBase64String(model.ImageBase64);
req.ContentLength = data.Length;
Stream stream = req.GetRequestStream();
stream.Write(data, 0, data.Length);
stream.Close();
}
}
}
使用base64 / FileReader發送原始二進制文件而不是增加~30%的大小
// sends the raw binary
fetch('http://example.com/upload', {method: 'post', body: file})
// Append the blob/file to a FormData and send it
var fd = new FormData()
fd.append('file', file, file.name)
fetch('http://example.com/upload', {method: 'post', body: fd})
// xhr = new ...
// xhr.open(...)
xhr.send(file) // or
xhr.send(fd) // send the FormData
通常在上傳文件時,盡量避免發送json,因為許多開發人員往往會出錯。 json中的二進制數據等於不良實踐(和更大的大小),例如:
$.post(url, {
name: '',
data: base64
})
盡可能使用FormData#append,或者如果您願意:
fd.append('json', json)
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.