简体   繁体   English

不带formData的图片上传

[英]Image upload without formData

I have created an application where an image to be uploaded.我创建了一个要上传图像的应用程序。 But the problem is I am sending a data object that is never equals to formData.但问题是我正在发送一个永远不等于 formData 的数据对象。 Because I modified(formatted) the data object as required to send to the server.因为我根据需要修改(格式化)了数据对象以发送到服务器。

<input type="file" name="imageUrl" id="photoFile">

Something like,就像是,

var data = {
 name: '',
 attributes: [{}, {}]
}

To this I want to add an image to be uploaded.为此,我想添加一个要上传的图像。 If I use form data, It would be something like this.如果我使用表单数据,它会是这样的。

var data = {
 name: '',
 attribute1: {},
 attribute2: {}
}

So, I formatted as requirement and I tried throughout the day.所以,我按照要求进行了格式化,并尝试了一整天。 But got nothing.却一无所获。

Use Jquery form with which you can upload files and manipulate the form data.使用 Jquery 表单,您可以上传文件并操作表单数据。 Use the following syntax:使用以下语法:

$('#form_id').ajaxForm({
                beforeSerialize: function($form, options){
                  // do the data manipulations here and send it to options["data"]
                  options["data"] = processed_data;
                  },
                 dataType:  'json',
                 success:  function(data){
                    //success functional logic.
                  }
              });

For more on Jquery form http://malsup.com/jquery/form/有关 Jquery 表单的更多信息http://malsup.com/jquery/form/

Convert to base64 using html canvas https://developer.mozilla.org/en-US/docs/Web/API/HTMLCanvasElement and send it as a string https://developer.mozilla.org/en-US/docs/Web/API/HTMLCanvasElement/toDataURL使用 html canvas https://developer.mozilla.org/en-US/docs/Web/API/HTMLCanvasElement转换为 base64 并将其作为字符串发送https://developer.mozilla.org/en-US/docs/Web /API/HTMLCanvasElement/toDataURL

const getImg64 = async() => {
  const convertImgToBase64URL = (url) => {
  console.log(url)
    return new Promise((resolve, reject) => {
      const img = new Image();
      img.crossOrigin = 'Anonymous';
      img.onload = () => {
          let canvas = document.createElement('CANVAS')
          const ctx = canvas.getContext('2d')
          canvas.height = img.height;
          canvas.width = img.width;
          ctx.drawImage(img, 0, 0);
          const dataURL = canvas.toDataURL();
          canvas = null;
          resolve(dataURL)
      }
      img.src = url;
    })
  }
  //for the demonstration purposes I used proxy server to avoid cross origin error
  const proxyUrl = 'https://cors-anywhere.herokuapp.com/'
  const image = await convertImgToBase64URL(proxyUrl+'https://image.shutterstock.com/image-vector/vector-line-icon-hello-wave-260nw-1521867944.jpg')
  console.log(image)
}
getImg64()

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM