【问题标题】:Image upload without formData不带formData的图片上传
【发布时间】:2017-02-06 13:43:31
【问题描述】:

我已经创建了一个要上传图像的应用程序。但问题是我正在发送一个永远不等于 formData 的数据对象。因为我根据需要修改(格式化)了数据对象以发送到服务器。

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

类似的,

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

为此,我想添加要上传的图像。 如果我使用表单数据,它会是这样的。

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

所以,我按照要求进行了格式化,并尝试了一整天。但一无所获。

【问题讨论】:

  • 您好,重新格式化您的代码并粘贴更多我们可以使用的内容:)
  • 后端——无论你的平台是什么——都有一个明确定义的接受文件数据的格式,我认为你不能只是重新格式化它并期望它正常工作。对不起,如果我误解了你。
  • 转换成base64怎么样?

标签: javascript jquery


【解决方案1】:

使用 Jquery 表单,您可以使用它上传文件和操作表单数据。使用以下语法:

$('#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.
                  }
              });

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

【讨论】:

    【解决方案2】:

    使用html画布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()
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2019-07-17
      • 2015-06-19
      • 2017-04-07
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多