vue.js:canvas作为文件上传到后端(vue.js3/thinkphp6)

发布时间 2023-07-08 13:23:43作者: 刘宏缔的架构森林

一,前端代码:

说明:前端使用vue.js3+axios,主要通过canvas.toBlob这个api实现canvas转文件上传

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
//截取选中的图片区域并上传文件
 const save = () => {
   const canvas = document.createElement('canvas')
   const ctx = canvas.getContext('2d')
  //截图
  ....
   //把canvas转blob实现上传
   canvas.toBlob(function(blob) {
        //上传
        upload(blob);
   })
 }
 
 //上传
 const upload = (blob) => {
   //上传时url
   let url = "/api/image/upload";
   //form
     var data = new FormData();
     let file = new File([blob], '上传的图片.png', { type: 'image/png'})
     data.append("file",file);
   //axios上传文件
   axios({
     method:"post",
     url:url,
     data:data,
     headers:{'Content-Type': 'multipart/form-data'},
   }).then((res) => {
         console.log('上传返回:');
         console.log(res.data);
         if (res.data.code == 0) {
           let data = res.data.data;
           console.log(data);
         } else {
           alert("error:"+res.data.msg);
         }
       }
   ).catch(err=>{
     console.log(err);
     alert('网络错误:'+err.message);
   });
 }

二,后端代码:

说明:后端框架使用了thinkphp6

1
2
3
4
5
6
7
8
9
10
11
12
13
14
//接收上传的图片文件并保存
    public function upload(){
         //接收文件并判断是否存在
        $postParams = $this->request->param();
        $file = request()->file('file');
        if ($file === null) {
            return Result::Error(10001,"文件不存在");
        }
 
        //保存到本地
        $destFile = '/data/work/tmpimg/a.png';
        $isUpload = move_uploaded_file($file->getPathname(),$destFile);
        return Result::Success(['msg'=>'上传成功']);
    }

说明:刘宏缔的架构森林—专注it技术的博客,
网站:https://blog.imgtouch.com
原文: https://blog.imgtouch.com/index.php/2023/07/08/vue-js-canvas-zuo-wei-wen-jian-shang-chuan-dao-hou-duan/
代码: https://github.com/liuhongdi/ 或 https://gitee.com/liuhongdi
说明:作者:刘宏缔 邮箱: 371125307@qq.com

三,查看效果:

服务端保存下的图片,是我们截取的canvas的一部分,
已保存成了文件,如图: