周晓楠

导航

 

七牛云 js上传视频
vue的html代码

//引入js
<script src="../js/plugins/jquery-2.1.1.js"></script>
<script src="../js/qiniu/plupload.full.min.js"></script>
<script src="../js/qiniu/qiniu.js?t=3"></script>
<style>
#pickfiles {
        padding: 10px;
        background: #000;
        border-radius: 5px;
        color: #fff;
    }
    .progress {
        color: red;
        font-size: 22px;
        margin-top: 20px;
    }
</style>
 <div class="form-group">
        <label class="control-label col-xs-12 col-sm-1"><span class="required">*</span>视频:</label>
      <div class="col-xs-12 col-sm-7">
          <span id='pickfiles'>上传视频</span>
          <span class="progress">{{progress}}</span>
          <span> <a :href="qiniu_video_url" target="_blank" v-if="qiniu_video_url!=''">点击查看视频</a></span>
          <input type="hidden" name="video_url" :value="qiniu_video_url">
      </div>
    </div>
  • 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

vue的js代码

 created:function(){
       //获取七牛云token和外部访问的URl
        this.getTokenMessage();
    },
     methods: {
        getTokenMessage(){
            var that=this;
            $.ajax({
                url: '/admin/qiniu/getToken',
                type: 'POST',
                data: {'_token':"{{ csrf_token() }}"},
                dataType : 'json',
                success: function (data) {
                    var obj = data;
                    console.log("~~~obj",obj);
                    // that.video_token=obj.data.uptoken;  //token
                    // that.video_upload_url=obj.data.domain; //外部访问url
                    that.initQiniu(obj.data.uptoken,obj.data.domain)
                }
            });
        },
        initQiniu (uptoken,domain){
            var that=this
            Qiniu.uploader({
                runtimes: 'html5,flash,html4',
                browse_button: 'pickfiles',
                // flash_swf_url: 'https://cdn.bootcss.com/plupload/2.1.1/Moxie.swf',
                flash_swf_url: 'Moxie.swf', //引入flash,相对路径
                chunk_size: '4mb',
                uptoken: uptoken,
                // uptoken_url: '',
                domain: domain,// bucket域名,下载资源时用到,必需
                get_new_uptoken: false,
                auto_start: true,
                max_retries: 3,
                filters: {
                    max_file_size: '100mb',
                    prevent_duplicates: false,
                    // Specify what files to browse for
                    mime_types: [
                        {title : '视频格式', extensions : 'mp4'} // 限定文件后缀上传格式上传
                    ]
                },
                init: {
                    'FilesAdded': (up, files) => {
                        console.log('文件就绪', files);
                    },
                    BeforeUpload: (up, file) => {
                        console.log('上传之前', file);
                    },
                    UploadProgress: (up, file) => {
                        console.log('上传中 file',file);
                        this.progress = file.percent + '%';
                    },
                    FileUploaded: (up, file, info) => {
                        // 每个文件上传成功后,处理相关的事情
                        // 其中 info 是文件上传成功后,服务端返回的json,形式如
                        // {
                        // "hash": "Fh8xVqod2MQ1mocfI4S4KpRL6D98",
                        // "key": "gogopher.jpg"
                        // }
                          res=JSON.parse(info)
                        that.qiniu_video_url = domain +'/'+ res.key; //获取上传成功后的文件的Url
                        console.log('获取上传成功后的文件的Url',that.qiniu_video_url)

                    },
                    Error: (up, err, errTip) => {
                        console.log('上传失败', err);
                    },
                    Key: (up, file) => {}
                }
            });
        },
       }
  • 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
  • 43
  • 44
  • 45
  • 46
  • 47
  • 48
  • 49
  • 50
  • 51
  • 52
  • 53
  • 54
  • 55
  • 56
  • 57
  • 58
  • 59
  • 60
  • 61
  • 62
  • 63
  • 64
  • 65
  • 66
  • 67
  • 68
  • 69
  • 70
  • 71
  • 72
  • 73
  • 74

php代码

//控制器文件
<?php
namespace app\admin\controller;
use app\common\controller\Backend;
use services\QiNiuService;
class  Qiniu extends Backend {
   public function getToken(){
      $data=QiNiuService::GetTokenUrl();
       return $this->result($data, 200, 'success');
   }

}

<?php
namespace services;
//引入七牛云的相关文件
use Qiniu\Auth as Auth;
use Qiniu\Storage\UploadManager;
use \think\facade\Config;
use think\Exception;
//七牛云上传
class QiNiuService {
    //得到七牛云token和访问url
    public static function GetTokenUrl(){
        // 需要填写你的 Access Key 和 Secret Key
        $accessKey = Config::get('qiniu.accessKey');
        $secretKey = Config::get('qiniu.secretKey');
        // 构建鉴权对象
        $auth = new Auth($accessKey, $secretKey);
        // 要上传的空间
        $bucket = Config::get('qiniu.bucket');
        $visit_domain=Config::get('qiniu.visit_domain');
        $token = $auth->uploadToken($bucket);
        return ['uptoken'=>$token,'domain'=>$visit_domain];
    }

}

七牛云上传图片(包括从相机获取的和从相册获取的)    七牛云上传视频       8.0手机调起相机        都会进行描述    多图片和多视频上传    获取图片后缀   隐藏软键盘

1、导入七牛云的依赖

  1.  
    //七牛云
  2.  
    api 'com.qiniu:qiniu-android-sdk:7.3.+'
  3.  
    api 'pub.devrel:easypermissions:0.4.3'
  4.  
    api 'com.qiniu:happy-dns:0.2.13'
  5.  
    api 'com.loopj.android:android-async-http:1.4.9'

2、添加七牛云的工具类

https://download.csdn.net/download/jing_80/10832747     可以下载,我已上传

3、因为出于保护数据   所以中间的字符用xxxxx代替,这两个变量在七牛云上可以获取到,这个很重要,这个是获取七牛云Token需要用到的,不过我们这里的token是我们的后台返给我的,所以各位小伙伴看情况而定

  1.  
    public static final String AccessKey = "-lOgC9xxxxxxxxxxxxiHIBDSrIZ";
  2.  
    public static final String SecretKey = "PYCGWxxxxxxxxxxxxxxxKw0F0v0B0Sty4m";

4、前面的准备工作做完之后,来吧,接下来我们要写真正的上传代码了,一步一步来

如果你是准备好了相机相册各种权限的 就不说了   直接看(2)

如果你是什么也没写,那就先添加上调用相机所用的权限吧! 先看(1)

(1)在res下创建xml文件

xml文件中的内容:

  1.  
    <?xml version="1.0" encoding="utf-8"?>
  2.  
    <paths xmlns:android="http://schemas.android.com/apk/res/android">
  3.  
    <root-path path="" name="camera_photos" />
  4.  
    </paths>

再在AndroidManifest中添加代码和权限    权限可能不够    需要什么再添加

  1.  
    <uses-permission android:name="android.permission.INTERNET" />
  2.  
     
  3.  
    <uses-feature android:name="android.hardware.camera" />
  4.  
    <!-- 相机权限 -->
  5.  
    <uses-permission android:name="android.permission.CAMERA" />
  6.  
    <!-- 写入SD卡的权限:如果你希望保存相机拍照后的照片 -->
  7.  
    <uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE" />
  8.  
    <!-- 读取SD卡的权限:打开相册选取图片所必须的权限 -->
  9.  
    <uses-permission android:name="android.permission.READ_EXTERNAL_STORAGE" />

在AndroidManifest中添加  这个provider和activity同级的

  1.  
    <!-- 8.0相机 -->
  2.  
    <provider
  3.  
    android:name="android.support.v4.content.FileProvider"
  4.  
    android:authorities="${applicationId}.provider"
  5.  
    android:exported="false"
  6.  
    android:grantUriPermissions="true">
  7.  
    <meta-data
  8.  
    android:name="android.support.FILE_PROVIDER_PATHS"
  9.  
    android:resource="@xml/file_path" />
  10.  
    </provider>

(2)七牛云上传代码

  1.  
    public class UploadDynamicActivity implements View.OnClickListener {
  2.  
     
  3.  
    private static final int REQUEST_CODE_VIDEO = 0x00000012;
  4.  
    private static final int REQUEST_CODE_CAMERA = 0x00000011;
  5.  
    private static final int REQUEST_CODE_ALBUM = 0x00000010;
  6.  
    private String upPath,videoThumb;
  7.  
    private String headpicPath;
  8.  
    private Uri uri;
  9.  
    private File file;
  10.  
     
  11.  
     
  12.  
    @SuppressLint("HandlerLeak")
  13.  
    private Handler handler = new Handler() {
  14.  
    @Override
  15.  
    public void handleMessage(Message msg) {
  16.  
    super.handleMessage(msg);
  17.  
    if (msg.what == 12) {
  18.  
    String headpicPaths = (String) msg.obj;
  19.  
    if (headpicPaths != null) {
  20.  
     
  21.  
    // headpicPaths是七牛云返回的地址 这里写自己的处理
  22.  
    }
  23.  
    }
  24.  
    }
  25.  
    };
  26.  
     
  27.  
    @Override
  28.  
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
  29.  
    super.onActivityResult(requestCode, resultCode, data);
  30.  
     
  31.  
    switch (requestCode) {
  32.  
    case REQUEST_CODE_CAMERA:
  33.  
    if (resultCode == RESULT_OK) {
  34.  
    upPath = file.getAbsolutePath();
  35.  
    break;
  36.  
    }
  37.  
     
  38.  
    case REQUEST_CODE_ALBUM:
  39.  
    if (resultCode == RESULT_OK) {
  40.  
    Uri uriAlbum = data.getData();
  41.  
    upPath = fromImageUriGetPath(uriAlbum);
  42.  
    break;
  43.  
    }
  44.  
     
  45.  
    case REQUEST_CODE_VIDEO:
  46.  
    if (resultCode == RESULT_OK) {
  47.  
    //从相册选取视频
  48.  
    Uri selectedVideo = data.getData();
  49.  
    upPath = fromVideoUriGetPath(selectedVideo);
  50.  
    break;
  51.  
    }
  52.  
    break;
  53.  
    }
  54.  
    }
  55.  
     
  56.  
    // 利用获取到的图片Uri 在获取到图片对应的path
  57.  
    private String fromImageUriGetPath(Uri uri) {
  58.  
    String[] filePathColumn = {MediaStore.Images.Media.DATA};
  59.  
    Cursor cursor = getContentResolver().query(uri,
  60.  
    filePathColumn, null, null, null);
  61.  
    cursor.moveToFirst();
  62.  
    int columnIndex = cursor.getColumnIndex(filePathColumn[0]);
  63.  
    //picturePath就是图片在储存卡所在的位置
  64.  
    String picturePath = cursor.getString(columnIndex);
  65.  
     
  66.  
    cursor.close();
  67.  
     
  68.  
    return picturePath;
  69.  
    }
  70.  
     
  71.  
    // 利用获取到的视频Uri 在获取到视频对应的path
  72.  
    private String fromVideoUriGetPath(Uri uri) {
  73.  
    String[] filePathColumn = {MediaStore.Images.Media.DATA};
  74.  
    Cursor cursor = getContentResolver().query(uri,
  75.  
    new String[]{MediaStore.Video.Media.DATA}, null, null, null);
  76.  
    cursor.moveToFirst();
  77.  
    int columnIndex = cursor.getColumnIndex(filePathColumn[0]);
  78.  
    //picturePath就是图片在储存卡所在的位置
  79.  
    String picturePaths = cursor.getString(columnIndex);
  80.  
     
  81.  
    //这个videoThumb是获取该视频缩略图的地址 至于怎么获取的缩略图 我的博客里有 获取网络的 获取本地的 只需要视频地址就可以
  82.  
    Bitmap netVideoBitmap = VideoFrameUtils.getLocalVideoBitmap(picturePaths);
  83.  
    videoThumb = VideoFrameUtils.saveBitmap(UploadDynamicActivity.this, netVideoBitmap);
  84.  
     
  85.  
    cursor.close();
  86.  
     
  87.  
    return picturePaths;
  88.  
    }
  89.  
     
  90.  
    //上传图片或视频到七牛云的方法
  91.  
    private void uploadInfoToQiNiu(final String path) {
  92.  
    new Thread(new Runnable() {
  93.  
    @Override
  94.  
    public void run() {
  95.  
    String picSuffix = getPicSuffix(path);
  96.  
    String randomNumCode = getRandomNumCode();
  97.  
    // 设置图片名字
  98.  
    SimpleDateFormat sdf = new SimpleDateFormat("yyyyMMddHHmmss");
  99.  
    String key = "icon_" + sdf.format(new Date()) + randomNumCode + "." + picSuffix;
  100.  
    UploadManager uploadManager = new UploadManager();
  101.  
     
  102.  
    //这个getQNToken需要从后台获取 或者是自己从七牛云上找方法获取
  103.  
     
  104.  
    uploadManager.put(path, key, getQNToken, new UpCompletionHandler() {
  105.  
    @Override
  106.  
    public void complete(String key, ResponseInfo info, JSONObject res) {
  107.  
    if (info.isOK()) {
  108.  
    //这个是你将图片上传之后七牛云给你返回的地址 这个需要传给你们的后台
  109.  
    headpicPath = "http://qiniu.bjmocang.com/" + key;
  110.  
     
  111.  
    Message message = handler.obtainMessage(12, headpicPath);
  112.  
    handler.sendMessage(message);
  113.  
    } else {
  114.  
    Log.e("tagxx", info.error);
  115.  
    }
  116.  
    }
  117.  
    }, null);
  118.  
    }
  119.  
    }).start();
  120.  
     
  121.  
    }
  122.  
     
  123.  
     
  124.  
    //调取相机
  125.  
    private void fromCamera() {
  126.  
    file = new File(Environment.getExternalStorageDirectory(), SystemClock.uptimeMillis() + ".jpg");
  127.  
    if (Build.VERSION.SDK_INT >= 24) {
  128.  
    uri = FileProvider.getUriForFile(this, BuildConfig.APPLICATION_ID + ".provider", file);
  129.  
    } else {
  130.  
    uri = Uri.fromFile(file);
  131.  
    }
  132.  
    Intent intent = new Intent(MediaStore.ACTION_IMAGE_CAPTURE);
  133.  
    intent.putExtra(MediaStore.EXTRA_OUTPUT, uri);
  134.  
    startActivityForResult(intent, REQUEST_CODE_CAMERA);
  135.  
    }
  136.  
     
  137.  
     
  138.  
    @Override
  139.  
    public void onClick(View v) {
  140.  
    switch (v.getId()) {
  141.  
    case R.id.相机:
  142.  
    fromCamera();
  143.  
    break;
  144.  
    case R.id.相册:
  145.  
    Intent intentAlbum = new Intent(Intent.ACTION_PICK);
  146.  
    intentAlbum.setDataAndType(MediaStore.Images.Media.EXTERNAL_CONTENT_URI, "image/*");
  147.  
    startActivityForResult(intentAlbum, REQUEST_CODE_ALBUM);
  148.  
    break;
  149.  
    case R.id.视频:
  150.  
    Intent intentVideo = new Intent(Intent.ACTION_PICK);
  151.  
    intentVideo.setDataAndType(MediaStore.Video.Media.EXTERNAL_CONTENT_URI, "video/*");
  152.  
    startActivityForResult(intentVideo, REQUEST_CODE_VIDEO);
  153.  
    break;
  154.  
    }
  155.  
    }
  156.  
     
  157.  
    @AfterPermissionGranted(1)//添加注解,是为了首次执行权限申请后,回调该方法
  158.  
    private void methodRequiresTwoPermission() {
  159.  
    String[] perms = {Manifest.permission.CAMERA, Manifest.permission.WRITE_EXTERNAL_STORAGE};
  160.  
    if (EasyPermissions.hasPermissions(this, perms)) {
  161.  
    //已经申请过权限,直接调用相机
  162.  
    // openCamera();
  163.  
    } else {
  164.  
    EasyPermissions.requestPermissions(this, "需要获取权限", 1, perms);
  165.  
    }
  166.  
    }
  167.  
     
  168.  
    //生成四位随机数
  169.  
    public static String getRandomNumCode() {
  170.  
    String codeNum = "";
  171.  
    int[] numbers = {0, 1, 2, 3, 4, 5, 6, 7, 8, 9};
  172.  
    Random random = new Random();
  173.  
    for (int i = 0; i < 4; i++) {
  174.  
    int next = random.nextInt(10000);
  175.  
    codeNum += numbers[next % 10];
  176.  
    }
  177.  
    return codeNum;
  178.  
    }
  179.  
     
  180.  
    /**
  181.  
    * 获取图片后缀
  182.  
    *
  183.  
    * @param img_path 图片或者视频路径
  184.  
    * @return
  185.  
    */
  186.  
    public static String getPicSuffix(String img_path) {
  187.  
    if (img_path == null || img_path.indexOf(".") == -1) {
  188.  
    return ""; //如果图片地址为null或者地址中没有"."就返回""
  189.  
    }
  190.  
    return img_path.substring(img_path.lastIndexOf(".") + 1).
  191.  
    trim().toLowerCase();
  192.  
    }
  193.  
     
  194.  
    //设置点击任意空白处隐藏键盘
  195.  
    @Override
  196.  
    public boolean dispatchTouchEvent(MotionEvent ev) {
  197.  
    if (ev.getAction() == MotionEvent.ACTION_DOWN) {
  198.  
    // 获得当前得到焦点的View,一般情况下就是EditText(特殊情况就是轨迹求或者实体案件会移动焦点)
  199.  
    View v = getCurrentFocus();
  200.  
    if (HideInputUtil.isShouldHideInput(v, ev)) {
  201.  
    hideSoftInput(v.getWindowToken());
  202.  
    }
  203.  
    }
  204.  
    return super.dispatchTouchEvent(ev);
  205.  
    }
  206.  
     
  207.  
    /**
  208.  
    * 隐藏软键盘 
  209.  
    *
  210.  
    * @param token
  211.  
    */
  212.  
    private void hideSoftInput(IBinder token) {
  213.  
    if (token != null) {
  214.  
    InputMethodManager im = (InputMethodManager) getSystemService(Context.INPUT_METHOD_SERVICE);
  215.  
    im.hideSoftInputFromWindow(token, InputMethodManager.HIDE_NOT_ALWAYS);
  216.  
    }
  217.  
    }
  218.  
     
  219.  
    }

5、补充一下,看很多小伙伴都说找不到这个工具类,在这里添加上。

  1.  
    public class VideoFrameUtils {
  2.  
    public VideoFrameUtils() {
  3.  
    }
  4.  
     
  5.  
    public static Bitmap getNetVideoBitmap(String videoUrl) {
  6.  
    Bitmap bitmap = null;
  7.  
    MediaMetadataRetriever retriever = new MediaMetadataRetriever();
  8.  
     
  9.  
    try {
  10.  
    retriever.setDataSource(videoUrl, new HashMap());
  11.  
    bitmap = retriever.getFrameAtTime(-1L);
  12.  
    } catch (IllegalArgumentException var7) {
  13.  
    var7.printStackTrace();
  14.  
    } finally {
  15.  
    retriever.release();
  16.  
    }
  17.  
     
  18.  
    return bitmap;
  19.  
    }
  20.  
     
  21.  
    public static Bitmap getLocalVideoBitmap(String localPath) {
  22.  
    MediaMetadataRetriever media = new MediaMetadataRetriever();
  23.  
    media.setDataSource(localPath);
  24.  
    Bitmap bitmap = media.getFrameAtTime(1L, 2);
  25.  
    return bitmap;
  26.  
    }
  27.  
     
  28.  
    public static Bitmap compressImage(Bitmap image) {
  29.  
    ByteArrayOutputStream baos = new ByteArrayOutputStream();
  30.  
    image.compress(CompressFormat.JPEG, 100, baos);
  31.  
    int options = 90;
  32.  
     
  33.  
    while(baos.toByteArray().length / 1024 > 800) {
  34.  
    baos.reset();
  35.  
    image.compress(CompressFormat.JPEG, options, baos);
  36.  
    if (options > 10) {
  37.  
    options -= 10;
  38.  
    }
  39.  
    }
  40.  
     
  41.  
    ByteArrayInputStream isBm = new ByteArrayInputStream(baos.toByteArray());
  42.  
    Bitmap bitmap = BitmapFactory.decodeStream(isBm, (Rect)null, (Options)null);
  43.  
    return bitmap;
  44.  
    }
  45.  
     
  46.  
    public static String saveBitmap(Context context, Bitmap mBitmap) {
  47.  
    String savePath = context.getApplicationContext().getFilesDir().getAbsolutePath();
  48.  
     
  49.  
    File filePic;
  50.  
    try {
  51.  
    filePic = new File(savePath + "/image/map.jpg");
  52.  
    if (!filePic.exists()) {
  53.  
    filePic.getParentFile().mkdirs();
  54.  
    filePic.createNewFile();
  55.  
    }
  56.  
     
  57.  
    FileOutputStream fos = new FileOutputStream(filePic);
  58.  
    mBitmap.compress(CompressFormat.JPEG, 100, fos);
  59.  
    fos.flush();
  60.  
    fos.close();
  61.  
    } catch (IOException var5) {
  62.  
    var5.printStackTrace();
  63.  
    return null;
  64.  
    }
  65.  
     
  66.  
    return filePic.getAbsolutePath();
  67.  
    }
  68.  
posted on 2020-10-14 21:36  周晓楠  阅读(419)  评论(0编辑  收藏  举报