首页
学习
活动
专区
圈层
工具
发布
社区首页 >问答首页 >将图像转换为Base64时缩小图像大小

将图像转换为Base64时缩小图像大小
EN

Stack Overflow用户
提问于 2017-01-12 10:16:42
回答 1查看 2.4K关注 0票数 1

我正在使用JavaScript中的文件阅读器,我需要将我的图像上传到WebApi中,并将其转换成字节数组并保存在服务器中,其工作正常,现在我的问题是base64字符串增加了图像的大小,假设我上传了30 it的图像,它在服务器中存储了389 it,如何将图像保存在相同大小或缩小图像大小需要帮助。

代码语言:javascript
复制
  //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();
     }
      }
    }
EN

回答 1

Stack Overflow用户

发布于 2017-01-12 22:17:34

用base64 64/FileReader发送原始二进制文件,而不是增加30%的大小

带取

代码语言:javascript
复制
// 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

代码语言:javascript
复制
// xhr = new ...
// xhr.open(...)

xhr.send(file) // or
xhr.send(fd) // send the FormData

通常,当上传文件时,尽量避免发送json,因为很多开发人员都会出错。json中的二进制数据等于错误的实践(以及更大的大小),例如:

代码语言:javascript
复制
$.post(url, {
  name: '',
  data: base64
})

尽可能多地使用FormData#append,或者如果您愿意的话:

代码语言:javascript
复制
fd.append('json', json)
票数 0
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/41610480

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档