首页 > 其他分享 >vue.js3:axios图片上传([email protected] / [email protected])

vue.js3:axios图片上传([email protected] / [email protected])

时间:2022-10-08 15:24:26浏览次数:84  
标签:axios 1.1 liuhongdi vue 3.2 file data

一,安装axios库

1,相关地址 官网:
https://axios-http.com/
代码地址:
https://github.com/axios/axios
2,安装
liuhongdi@lhdpc:/data/vue/axios$ npm install --save axios
added 5 packages in 3s
3,查看已安装的库的版本:
liuhongdi@lhdpc:/data/vue/imgtouch$ npm list axios
[email protected] /data/vue/imgtouch
└── [email protected]

说明:刘宏缔的架构森林是一个专注架构的博客,地址:https://www.cnblogs.com/architectforest

         对应的源码可以访问这里获取: https://github.com/liuhongdi/
         或: https://gitee.com/liuhongdi

说明:作者:刘宏缔 邮箱: [email protected]

二,js代码

<template>
<div>
  <div style="width:800px;margin: auto;display: flex;flex-direction: column;">
  请选择上传图片:
  <input type="file" id="back" ref="backfile" @change="handleFile" /><br/>
  <div id="imglist" style="width:100%;">
    <div v-for="(item,i) in selFiles" :key="i" style="float:left;margin-left: 20px;margin-top: 20px;height:150px;position:relative;">
      <img :src="item.fileimg"  style="height:150px;"/>
    </div>
  </div>
    <div>
  <input type="button" value="上传" @click="upload" />
    </div>
  </div>
</div>
</template>

<script>
import {ref} from "vue";
import axios from 'axios';

export default {
  name: "ImgUpload",
  setup() {
    //选中的图片文件,保存在数组中
    const selFiles = ref([]);
    //选中图片后的处理
    const handleFile = () => {
      let filePaths = window.event.target.files;
      //清空原有缩略图
      if (filePaths.length === 0) {
        //未选择,则返回
        return
      } else {
        //清空数组中原有图片
        selFiles.value.length = 0;
      }
      //把新选中的图片加入数组
      for( var i=0;i<filePaths.length; i++ ){
        let file = filePaths[i];
        let one = {
          fileimg:URL.createObjectURL(file),  //预览用
          file:file,
        }
        selFiles.value.push(one);
      }
    }

    //上传
    const upload = () => {
      //判断是否选中文件
      if (selFiles.value.length == 0) {
        alert("请在上传前先选中文件!");
        return;
      }
      var file = selFiles.value[0].file;
      if (typeof(file) === "undefined") {
        alert("请在上传前先选中文件!");
        return;
      }
      // 创建一个表单数据
      var data = new FormData();

      //遍历文件并上传
      for( var i=0;i<selFiles.value.length; i++ ){
        let fileOne = selFiles.value[i].file;
        console.log("上传:"+fileOne.name)
        data.append("file",fileOne);
      }

      data.append("userName","laoliu");

      let url = "/api/image/uploadone";
      //axios上传文件
      axios({
        method:"post",
        url:url,
        data:data,
        headers:{'Content-Type': 'multipart/form-data'},
      }).then((res) => {
            //console.log(res.data);
            if (res.data.code == 0) {
              let data = res.data.data;
              console.log(data);
              let userName = data.userName;
              let imageUrl = data.imageurl;
              alert("success:提交的用户名:"+userName+";image:"+imageUrl);
            } else {
              alert("error:"+res.data.msg);
            }
          }
      ).catch(err=>{
        console.log(err);
        alert('网络错误:'+err.message);
      });
    }

     return {
       selFiles,
       handleFile,
       upload,
     }
  }
}
</script>

<style scoped>

</style>

三,php代码:基于thinkphp6

1,创建目录:
liuhongdi@lhdpc:/var/www/html$ sudo mkdir goodsimage
[sudo] liuhongdi 的密码:
liuhongdi@lhdpc:/var/www/html$ sudo chmod 777 goodsimage
2,在.env中添加配置
[GOODSIMAGE]
GOODS_IMAGE_DIR=/var/www/html/goodsImage
GOODS_IMAGE_HOST=http://192.168.219.6/goodsImage
3,配置php 在config目录下,创建images.php
<?php
return [
   "goodsImageDir"=>env('goodsimage.goods_image_dir' ),
   "goodsImageHost"=>env('goodsimage.goods_image_host'),
];
4,php代码:
<?php
namespace app\controller;

use app\BaseController;
use app\result\Result;
use \think\facade\Config as GConfig;

class Image extends BaseController
{
    //接收上传的一个图片文件
    public function uploadOne(){
        $postParams = $this->request->param();
        $file = request()->file('file');
        if ($file === null) {
            return Result::Error(10001,"文件不存在");
        }

        $imageUrl = "";

            //得到图片的源文件路径和目标文件路径
            $basedir = GConfig::get('images.goodsImageDir');
            $subdir = date("Ymd");
            $dir = $basedir."/".$subdir;
            if (!is_dir($dir)) {
                mkdir($dir);
            }
            $filename = uniqid();
            //得到文件名
            $destFile = $dir."/".$filename.".".$file->getOriginalExtension();
            //保存到本地
            $isUpload = move_uploaded_file($file->getPathname(),$destFile);
            //如成功返回图片的url
            if ($isUpload) {
                $savename[] = $subdir."/".$filename.".".$file->getOriginalExtension();
                $host = GConfig::get('images.goodsImageHost');
                $imageUrl = $host."/".$subdir."/".$filename.".".$file->getOriginalExtension();
            }

        return Result::Success(["userName"=>$postParams['userName'],"imageurl"=>$imageUrl]);
    }
}

四,测试效果

五,查看vue框架的版本: 

liuhongdi@lhdpc:/data/vue/pdf/image2pdf$ npm list vue
[email protected] /data/vue/pdf/image2pdf
├─┬ @vue/[email protected]
│ └─┬ @vue/[email protected]
│   ├─┬ @vue/[email protected]
│   │ └── [email protected] deduped invalid: "2.x" from node_modules/@vue/babel-preset-jsx
│   └── [email protected] deduped
└─┬ [email protected]
  └─┬ @vue/[email protected]
    └── [email protected] deduped

 

标签:axios,1.1,liuhongdi,vue,3.2,file,data
From: https://www.cnblogs.com/architectforest/p/16769023.html

相关文章

  • Vue2路由
    路由前端路由:不同的网址对应各自的页面vue的前端路由:SPA应用要做出路由效果,就得判断当前网址,然后切换组件vue-router就是专门做切换组件的功能,它是一个单独的技术,......
  • Vue2组件
    组件创建组件的定义:实现应用中局部功能代码和资源的集合定义组件Vue.extend(option)option:和nnewVue(option)里的option几乎一致,但有点区别el不写原因:最终所有......
  • Vue3 项目在 H5 + ios 环境中,input 输入框在输入中文未选中汉字时会触发 chang 事件,导
    省流版:看解决3环境vue3+vant+H5需求input输入框为验证码(隐含需求:用户接收到验证码时,需要复制验证码后可以点击输入法的联想词直接输入验证码,且需要仅能输入英文......
  • 【Vue2】一文弄懂前端路由
    一、对路由的理解1.什么是路由路由其实就是一组键值对or映射关系,在一个路由中应包含最基本的路径和组件信息。示例如下:上面展示的是一个路由组,即用"[]"将一组路由写在一......
  • Vue Hash模式和History模式
    首先,这两个模式都是在单页前端应用下的概念Hash模式的url后面会有一个“#”号(这个看起来会有点奇怪)。当改变#后面的部分是不会去请求后端的,仅在前端进行切换,所以在对一个H......
  • 1 1.1.1.1 1.1.2 1.3 2 2.1 ...这样的数据sql排序
    ----其中wbscode为1 1.1.1 1.1.2这样的编码。主要关注的地方为:1分解函数  2.根据分解函数进行行转列  3最终合并数据去重 -----分解函数CREATEFUNCTI......
  • vue2双向绑定原理:深入响应式原理defineProperty、watcher、get、set
    响应式是什么?Vue最独特的特性之一~就是我们在页面开发时,修改data值的时候,数据、视图页面需要变化的地方变化。主要使用到哪些方法?用 Object.defineProperty给watcher对......
  • Vue中常用的几种传值方式
    Vue中常用的几种传值方式 1.父传子父传子的实现方式就是通过props属性,子组件通过props属性接收从父组件传过来的值,而父组件传值的时候使用v-bind将子组件中预留的......
  • vue-cli脚手架的安装
    vue-cli提供一个官方命令行工具,可用于快速搭建大型单页应用。现如今,随着vue.js越来越火爆,更多的项目都用到vue进行开发,在实际的开发项目中,如何搭建开发脚手架呢,今天我分享......
  • 移动端 element + vue 二次封装上传图片的组件
    功能:支持预览、长按图片保存、删除项目中使用:1<el-form-itemlabel="上传照片"class="ml30">2<e-upload-image3v-model="image"4......