我在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();
}
}
}
答案 0 :(得分:0)
使用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)