其他分享
首页 > 其他分享> > js上传图片预览

js上传图片预览

作者:互联网

html

如果有头像了,显示头像 没有为空

<div class="col-sm-2">
<img id="preview_img" src="{{ !empty($user->avatar) ? $user->avatar : '' }}" alt="" class="img-rounded" style="border-radius:500px; width:100px;heigith:100px;">
<input class=" file-loading preview_input" type="file" value="用户名" style="width:72px" id="avatar" name="avatar" onchange="mypit()">

</div>

js
<script>
function mypit() {

var myfiles = document.getElementById("avatar"); //获取点击按钮的对象

var url = '';

url = window.URL.createObjectURL(myfiles.files[0]); //获取forms中的文件,并赋值给url,每次调用URL.crreateObjectURl方法时,都会创建一个对象。

document.getElementById("preview_img").src = url; //获取img标签对象的src,并将url赋值给img标签的src属性,这是完成打印的一步。

}
</script>

php 上传 使用oss阿里云比较方便 下个sdk 封装下
<?php

namespace Brady\Tool\Upload;

/**
 * Class Oss
 * 简单上传单文件 方便上传图片而已 默认存储桶后台阿里云建好了
 * https://github.com/aliyun/aliyun-oss-php-sdk
 * composer require aliyuncs/oss-sdk-php
 * @package Brady\Tool\Upload
 */

use Brady\Tool\Exception\ExceptionResult;
use OSS\OssClient;
use OSS\Core\OssException;

class Oss
{
	public $accessKeyId;
	public $accessKeySecret;
	public $endpoint;
	public $bucket;

	public $ossClient;


	public function __construct($config)
	{
		if (empty($config) || empty($config['accessKeyId']) ||
			empty($config['accessKeySecret']) || empty($config['endpoint']
				|| empty($config['bucket'])
			)) {
			ExceptionResult::throwException("参数错误", true);
		}
		$this->accessKeyId = $config['accessKeyId'];
		$this->accessKeySecret = $config['accessKeySecret'];
		$this->endpoint = $config['endpoint'];
		$this->bucket = $config['bucket'];

		$this->ossClient = new OssClient($this->accessKeyId, $this->accessKeySecret, $this->endpoint);

	}

	/**
	 * @param $local_file 本地文件 可以带路径 /www/a.php
	 * @param $remote_file 上传到服务器的路径和文件名 /test/a.php
	 */
	public function upload($local_file, $remote_file)
	{
		try {
			$res = $this->ossClient->uploadFile($this->bucket, $remote_file, $local_file);
			return $res;
		} catch (OssException $e) {
			ExceptionResult::throwException($e->getMessage(), true);
		}

	}

}

  



public function uploadAvatar($request)
{

$config = [
'accessKeyId'=>env("accessKeyId"),
'accessKeySecret'=>env("accessKeySecret"),
'endpoint'=>env("endpoint"),
'bucket'=>env("bucket"),
];

$oss = new Oss($config);
$res = $oss->upload($request->file('avatar'),"jianshu/avatar/".md5(time()).".jpg");

return isset($res['oss-request-url']) ? $res['oss-request-url'] : '';

}

标签:预览,url,上传,oss,js,avatar,file,accessKeyId,config
来源: https://www.cnblogs.com/php-linux/p/11665970.html