上传data image图片

最近在项目中有这么一个需求,就是上传一个视频文件,然后要获取视频文件的第一帧图片,这个可以通过canvas获取得到,得到的是一个dataURL,之后还要将这个图片上传到云,这个时候如何操作就不清楚了,于是乎,google一番,总结如下:

  1. 将dataURL转成Blob
  2. 利用formData
  3. 异步上传
function b64toBlob(b64Data, contentType='', sliceSize=512) {
        const byteCharacters = atob(b64Data);
        const byteArrays = [];

        for (let offset = 0; offset < byteCharacters.length; offset += sliceSize) {
            const slice = byteCharacters.slice(offset, offset + sliceSize);

            const byteNumbers = new Array(slice.length);
            for (let i = 0; i < slice.length; i++) {
                byteNumbers[i] = slice.charCodeAt(i);
            }

            const byteArray = new Uint8Array(byteNumbers);

            byteArrays.push(byteArray);
        }

      const blob = new Blob(byteArrays, {type: contentType});
      return blob;
}
// dataURL to blob

// 假设一个dataURL
const ImageURL = "data:image/jpeg;base64,abcdefg

// Split the base64 string in data and contentType
const block = ImageURL.split(";");

// Get the content type of the image
const contentType = block[0].split(":")[1];// In this case "image/jpeg"

// get the real base64 content of the file
const realData = block[1].split(",")[1];// In this case "R0lGODlhPQBEAPeoAJosM...."

// Convert it to a blob to upload
var blob = b64toBlob(realData, contentType);
// new a formData

const formData = new FormData();
formData.append('blob', blob);
// upload

$.ajax({
    url:url,
    data: formData
    type:"POST",
    contentType:false,
    processData:false,
    error:function(err){
    },
    success:function(data){
    },
});

你可能感兴趣的:(上传data image图片)