1,php代码
1 <?php 2 header('Access-Control-Allow-Origin:*'); 3 $link = mysqli_connect("localhost","root","123456",'myuser'); 4 mysqli_query($link,"set names utf8"); 5 6 $_name = $_POST["uName"]; //用户名 7 8 $_imgUrl = $_FILES["uImg"]; 9 //数组 [name: "h1.jpg" type: "image/jpeg" tmp_name: "C:WindowsTempphpB83A.tmp" error: 0size: 27720] 10 //重命名图片: 11 $extName = explode(".",$_imgUrl["name"]);//?????? 12 $fileExtName = $extName[count($extName)-1]; //获取扩展名 13 $fileName = "imgs/".time().".".$fileExtName; //重命名 15756987.jpg //图片存储位置 14 15 move_uploaded_file($_imgUrl["tmp_name"], $fileName); 16 17 $sql = "insert into mytable(_name,_imgUrl) values('{$_name}','{$fileName}')"; 18 if(mysqli_query($link,$sql)){ 19 $arr = array("msg"=>"添加成功","code"=>200); 20 echo json_encode($arr); 21 }else{ 22 $arr = array("msg"=>"no","code"=>300); 23 echo json_encode($arr); 24 } 25 26 ?>
2,vue简单代码
<template> <div id="app"> <form class="form" id="formMood" style="margin-top:10px;"> 会员名称:<input type="text" name="uName" id="uName"><br /> 会员头像:<input type="file" name="uImg" id="uImg"> </form> <button class="btn btn-primary" @click="sendMood">添加会员</button> </div> </template> <script> //import request from "./request/request.js"; import axios from "axios" export default { data(){ return({ page:1 }) }, methods:{ sendMood(){ var uName = document.getElementById('uName').value; //获取文字 var uImg = document.getElementById('uImg').files; //获取图片 //图片上传 var formdata = new FormData(); //创建图片上传对象 formdata.append("uName",uName); //添加文字 formdata.append("uImg",uImg[0]); //添加图片 //执行上传 axios.post("http://localhost:8888/addUserDataPic.php",formdata).then(res=>{ console.log(res) }) } } } </script>