Ajax to achieve image upload

In "Node.js+express+MySQL User Avatar Modification Using Qiniu Cloud" , we have implemented the H5 app made with MUI to upload pictures. Now the company's PC needs to upload pictures, but the interface for uploading pictures has been written before. It is the interface mentioned in "Node.js+express+MySQL User Avatar Modification Using Qiniu Cloud" .
Now all the front end has to do is adapt to this interface. Generally, the form is submitted and the ajax used is displayed.
HTML code:

<input type="file" id="uploadFile" onchange="inputchange('5')" filetype="image/*"/>

front-end js code

// 图片选择改变事件
function inputchange(tag){
    var inputTag = 'uploadFile' + tag;
    var file = document.getElementById(inputTag);
    if(window.FileReader){//chrome,firefox7+,opera,IE10+
          oFReader = new FileReader();
          oFReader.readAsDataURL(file.files[0]);
          oFReader.onload = function (oFREvent) {
              uploadImage(oFREvent.target.result,tag);
         // oFREvent.target.result  结果就是base64的数据
          };
      }
}
// 图片上传
function uploadImage(imageData,tag){
    $.ajax({
        url: '/api/upload',
        data: {
            imgData: imageData // 图片数据流
        },
        dataType: 'json',
        type: 'post',
        timeout: 10000,
        success: function(data) {
            if (data.status == 100 ) {
                var img = '#image' + tag;
                $(img).attr('src',data.imageUrl);
            }else{
                alert('图片上传失败!');
            }
        },
        error: function(xhr, type, errorThrown) {
            alert('网络异常,请稍后再试!');
        }
    });
}

The main focus here is the use of FileReader .

Guess you like

Origin http://43.154.161.224:23101/article/api/json?id=325375558&siteId=291194637