前臺頁面上傳data image圖片,java後臺接收圖片保存

最近在項目中有這麼一個需求,就是上傳一個視頻文件,然後要獲取視頻文件的第一幀圖片,這個可以通過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 = "轉成Base64的變量";

// 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){
    },
});

 

 後臺接受代碼

@RequestMapping(value = "/uploadImage")
@ResponseBody
public ApiMessage uploadImage(MultipartFile file, HttpServletRequest request) {
  try {
    //自定義處理圖片保存方法     
return ApiMessage.succeed(Utils.getImageUrl2(file));   } catch (Exception e) {     return ApiMessage.error();   } }

 

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章