700字范文,内容丰富有趣,生活中的好帮手!
700字范文 > VUE+axios+php实现图片上传

VUE+axios+php实现图片上传

时间:2018-12-01 02:01:27

相关推荐

VUE+axios+php实现图片上传

前端部分

执行函数,注意file那有个await,获取到文件数据后,装在FormData里面,然后调用下文axiosuploadFile

async uploadFiles() {let inputObj = document.createElement("input");let file = await new Promise((res) => {inputObj.setAttribute("id", "file");inputObj.setAttribute("type", "file");inputObj.setAttribute("name", "file");inputObj.setAttribute("style", "visibility:hidden");document.body.appendChild(inputObj);inputObj.click();document.querySelector("#file").addEventListener("change", (e) => {console.log(e.target.files);res(e.target.files)});});let formdata = new FormData()formdata.append('myFile', file[0])await this._http.uploadFile(formdata).then(console.log);document.body.removeChild(inputObj)},

http请求集中管理

async uploadFile(file) {return axios.post(`/Upload.php`,file,{headers: {"Content-Type": "multipart/form-data"}})}

php后端部分

接收参数,调用uploadFile

<?phpheader('content-type:text/html;charset=utf-8');$fileInfo=$_FILES["myFile"];$maxSize=10485760;//10M,10*1024*1024$allowExt=array('jpeg','jpg','png','tif');$path="uploads";include_once 'UploadFile.php';uploadFile($fileInfo, $path, $allowExt, $maxSize);

封装uploadFile函数

<?phpfunction uploadFile($fileInfo, $path, $allowExt, $maxSize){$filename = $fileInfo["name"];$tmp_name = $fileInfo["tmp_name"];$size = $fileInfo["size"];$error = $fileInfo["error"];$type = $fileInfo["type"];//服务器端设定限制$ext = pathinfo($filename, PATHINFO_EXTENSION);//目的信息if (!file_exists($path)) {mkdir($path, 0777, true);chmod($path, 0777);}$uniName = md5(uniqid(microtime(true), true)) . '.' . $ext;$destination = $path . "/" . $uniName;if ($error == 0) {if ($size > $maxSize) {exit("上传文件过大!");}if (!in_array($ext, $allowExt)) {exit("非法文件类型");}if (!is_uploaded_file($tmp_name)) {exit("上传方式有误,请使用post方式");}//判断是否为真实图片(防止伪装成图片的病毒一类的if (!getimagesize($tmp_name)) {//getimagesize真实返回数组,否则返回falseexit("不是真正的图片类型");}if (@move_uploaded_file($tmp_name, $destination)) {//@错误抑制符,不让用户看到警告echo "文件" . $filename . "上传成功!";} else {echo "文件" . $filename . "上传失败!";}} else {switch ($error) {case 1:echo "超过了上传文件的最大值,请上传2M以下文件";break;case 2:echo "上传文件过多,请一次上传20个及以下文件!";break;case 3:echo "文件并未完全上传,请再次尝试!";break;case 4:echo "未选择上传文件!";break;case 7:echo "没有临时文件夹";break;}}return $destination;}

本内容不代表本网观点和政治立场,如有侵犯你的权益请联系我们处理。
网友评论
网友评论仅供其表达个人看法,并不表明网站立场。