MENU

Catalog

input图片上传至七牛云+后端

November 16, 2020 • Read: 81 • JavaScript

Grit

input-MDN

  1. input标签type为 file
  2. accept指定可接受文件类型;accept=".jpg, .jpeg, .png"
  3. 使用change来监听上传时间
  4. 生成图片预览图: URL.createObjectURL(curFiles[i]);语法: objectURL = URL.createObjectURL(object);不使用时通过 URL.revokeObjectURL() 来释放;
  5. 获得图片大小
     function returnFileSize(number) {
       if(number < 1024) {
             return number + 'bytes';
         } else if(number >= 1024 && number < 1048576) {
             return (number/1024).toFixed(1) + 'KB';
         } else if(number >= 1048576) {
             return (number/1048576).toFixed(1) + 'MB';
           }
     }

6.访问上传的文件:(这里只指定上传一个图片的情况)

        const selectedFile = document.getElementById('input').files[0];
        //获取文件信息
        selectedFile.name/.size/.type

7.上传图片

//创建一个新formData对象,然后将上传的图片信息放进去;
    this.formData = new FormData();
    this.formData.append("img", this.uploadFile);

function sendFile(){
    const url = 'xxxxx';
    const xhr = new XMLHttpRequest();
    const formData = new FormData();

    xhr.open('POST',url,true);
    xhr.onreadystatechange = function(){
        if(xhr.readyState === 4 && xhr.stateCode === 200){
            //handle response
        }
    };
    formData.append('img',selectedFile)
    xhr.send(formData)
}

后端

需要的模块:qiniu;multiparty

1.获取上传的图片:

    ...
  
  let form = new multiparty.Form();
  form.parse(req, function (err, key, file) {
        //key表单内容;file上传的图片,文件等;
    ...
  })
  

2.上传至七牛云

    // 创建上传凭证
const accessKey = ''    //accessKey 
const secretKey = ''    //secretKey 
const mac = new qiniu.auth.digest.Mac(accessKey, secretKey)
const options = {
    scope: '',         //对象存储空间名字
    returnBody: '{"key":"$(key)","hash":"$(etag)","fsize":$(fsize),"bucket":"$(bucket)","name":"$(x:name)"}'
    //返回的格式
}
    //获取token,
      var putPolicy = new qiniu.rs.PutPolicy(options);
      var uploadToken = putPolicy.uploadToken(mac);

        //
      let config = new qiniu.conf.Config()
      config.zone = qiniu.zone.Zone_z2 //  空间对应机房
      let putExtra = new qiniu.form_up.PutExtra() //  生成表单提交额外参数
      let formUploader = new qiniu.form_up.FormUploader(config) //  生成表单上传的类
      formUploader.putFile(uploadToken, imgName/* 图片的名字 */, file/* 上传的文件 */, putExtra, function (respErr, respBody, respInfo) {
          
      })

81