首页
学习
活动
专区
圈层
工具
发布
社区首页 >问答首页 >flutter :如何通过视频将数据传递到我的php页面

flutter :如何通过视频将数据传递到我的php页面
EN

Stack Overflow用户
提问于 2020-11-24 02:33:19
回答 1查看 47关注 0票数 0

我需要通过视频,我想上传的数据,但我不知道如何做,就像这些数据,我需要传递它与视频到php页面

代码语言:javascript
复制
var data = {
      "fileInput": videoFile.path,
      "titleInput": titleController.text,
      "descriptionInput": descriptionController.text,
      "privacyInput": selectedCategorise.value,
      "categoryInput": listcategory.map((e) => {e['name']}),
    };

我知道如何在没有视频的情况下传递它,像这样的函数我传递电子邮件和密码

代码语言:javascript
复制
`signin() async {
    var formdata = formstatesignin.currentState;
    if (formdata.validate()) {
      formdata.save();
      var data = {"email": email.text, "password": password.text};
      var url = "http://10.0.2.2/mobtech2/login.php";
      var response = await http.post(url, body: data);
      var responsebody = jsonDecode(response.body);
      if (responsebody['status'] == "success") {
        savePref(responsebody['username'], responsebody['email'],
            responsebody['id']);
        Navigator.of(context).pushNamed("homepage");
      } else {
        Navigator.of(context).pop();
      }
    } else {
      print("Not vaild");
    }
  }`

这是我想要将数据传递给它的函数

代码语言:javascript
复制
`Future uploadVideo(File videoFile) async {
    var uri = Uri.parse("http://10.0.2.2/videoTube/file_upload.php");
    var request = new http.MultipartRequest("POST", uri);

    var multipartFile =
        await http.MultipartFile.fromPath("video", videoFile.path);
    request.files.add(multipartFile);
    http.StreamedResponse response = await request.send();
    response.stream.transform(utf8.decoder).listen((value) {
      print(value);
    });
    //final response = await http.post(uri, body: data);

    if (response.statusCode == 200) {
      print("Video uploaded");
    } else {
      print("Video upload failed");
    }
  }`

此代码用于php中的类处理。

代码语言:javascript
复制
`<?php

include "config.php";

if (!isset($_POST["video"])) {
    echo "No video sent to page";
    exit();
}

// 1) create file Uplaod Data
$videoUploadData = new VideoUploadData(
                            $_FILES["video"], 
                            $_POST["titleInput"],
                            $_POST["descriptionInput"],
                            $_POST["privacyInput"],
                            $_POST["categoryInput"],
                            "REPLACE-THIS"    
                        );
// 2) Process video data (upload)
$videoProcessor = new VideoProcessor($con);
$wasSuccessful = $videoProcessor->upload($videoUploadData);

?>`

php中类VideoUploadData的以下代码

代码语言:javascript
复制
`<?php
class VideoUploadData{

    public $videoDataArray, $title, $description, $privacy, $category, $uploadedBy;

    public function __construct($videoDataArray, $title, $description, $privacy, $category, $uploadedBy) {
        $this->videoDataArray = $videoDataArray;
        $this->title = $title;
        $this->description = $description;
        $this->privacy = $privacy;
        $this->category = $category;
        $this->uploadedBy = $uploadedBy;
    }
}
?>`

php中类VideoProcessor的以下代码

代码语言:javascript
复制
`<?php

class VideoProcessor{

    private $con;
    private $sizeLimit = 500000000;
    private $allowedTypes = array("mp4", "flv", "webm", "mkv", "vob", "ogv", "ogg", "avi", "wmv", "mov", "mpeg", "mpg");
    public function __construct($con) {
        $this->con = $con;
    }

    public function upload($videoUploadData) {

        $targetDir = "uploads/videos/";
        $videoData = $videoUploadData->videoDataArray;

        $tempFilePath = $targetDir . uniqid() . basename($videoData["name"]);

        $tempFilePath = str_replace(" ", "_", $tempFilePath);

        $isValidData = $this->processData($videoData, $tempFilePath);

        if (!$isValidData) {
            return false;
        }

        if (move_uploaded_file($videoData["video"]["tmp_name"], $tempFilePath)) {

            $finalFilePath = $targetDir . uniqid() . ".mp4";

            if (!$this->insertVideoData($videoUploadData, $finalFilePath)) {
                echo "Insert query failed";
                return false;
            }

        }
    }

    private function processData($videoData, $filePath) {

        $videoType = pathInfo($filePath, PATHINFO_EXTENSION);

        if (!$this->isValidSize($videoData)) {
            echo "File too large. Can't be more than" . $this->sizeLimit . " bytes";
            return false;
        }

        else if (!$this->isValidType($videoType)) {
            echo "Invalid file type";
            return false; 
        }

        else if ($this->hasError($videoData)) {
            echo "Error code: " . $videoData["error"];
            return false;
        }

        return true;

    }

    private function isValidSize($data) {
        return $data["size"] <= $this->sizeLimit;
    }

    private function isValidType($type) {
        $lowercased = strtolower($type);
        return in_array($lowercased, $this->allowedTypes);
    }
    private function hasError($data) {
        return $data["error"] != 0;
    }

    private function insertVideoData($uploadData, $filePath){}

}

?>`
EN

回答 1

Stack Overflow用户

发布于 2020-11-24 20:34:22

是的,您可以使用dio包上传带有名称和标题等描述的视频

这是一个例子,我用来上传一个带有一些描述的视频到我的服务器后端,当你使用函数_upload(video1)时使用MultipartFile,我将视频作为参数传递,但如果你愿意,你可以用其他方法来做,我还设置了视频上传进度的进度指示器。

代码语言:javascript
复制
    // create listing,post and upload video to the server

  void _upload(video1) async {

    // get variables from shared preferences
    token = await SharedPreferencesProvider.getUserToken();
    userId = await SharedPreferencesProvider.getUserId();

    // api to upload video
    // Post a video to 
    var url = 'https://example.com/api/v1/video';
    var video1Path;
    if (video1 == null) {
      return;
    } else {
      video1Path = await MultipartFile.fromFile(video1.path);
    }

    FormData data = FormData.fromMap({
      "title": title,
      "products": "1",
      "description": description,
      "category_id": categoryId,
      "category_name": categoryName,
      "longitude": _longitude,
      "latitude": _latitude,
      "video1": video1Path,
    });

    Dio dio = new Dio();
    dio.options.headers["Authorization"] = "Bearer $token";
    dio.post(url, data: data, onSendProgress: (int sent, int total) {
      setState(() {
        _isUploading = true;
        // show a progress %
        progressString ='uploading :' + ((sent / total) * 100).toStringAsFixed(0) + "%";
        if ( ((sent / total) * 100).toStringAsFixed(0) == '100'){
          progressString = 'Saving...';
        }
        //progressString = ((sent / total) * 100).toStringAsFixed(0) + "%";
      });

    }).then((response) async => {
      setState(() {

        progressString = DemoLocalizations.of(context).uploadCompleted;
      }),
      print(response),

      //after successful product post we redirect to(Main page)
      goHome()
    })
        .catchError((error) => print(error));
  }
票数 1
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/64974295

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档