Swift上传视频到Http服务器?

时间:2016-02-26 07:23:35

标签: ios swift ios9 nsurlsession

我正在尝试将视频上传到我的服务器。 我从相册中选择视频,但是“致命错误:在解开可选值时意外地发现了nil”。

请查看以下代码以获取更多信息。

let videoURL: String = NSBundle.mainBundle().pathForResource("IMG_2859", ofType: "MOV")!
// var videoData: NSData = NSData.dataWithContentsOfURL(NSURL.fileURLWithPath(videoURL))!
print(videoURL)
let data = NSData(contentsOfFile: videoURL)

print(data)

let session = NSURLSession.sharedSession()
let request = NSMutableURLRequest()
print(session)
print(request)

request.URL =  NSURL(string:  "uploadvideo/uploadtoserver?user_email=\(candit_email)")
print(request.URL)

request.HTTPMethod = "POST"

let boundary = "------------------------8744f963ff229392"
request.addValue("multipart/form-data; boundary=\(boundary)", forHTTPHeaderField: "Content-Type")

let postData = NSMutableData()
postData.appendData("--\(boundary)\r\n".dataUsingEncoding(NSUTF8StringEncoding)!)

print("Upload Video File1")
postData.appendData("Content-Disposition: form-data; name=\"filedata\"; filename=\"MOV\"\r\n".dataUsingEncoding(NSUTF8StringEncoding)!)
 print("Upload Video File2")

postData.appendData("Content-Type: video/x-msvideo\r\n\r\n".dataUsingEncoding(NSUTF8StringEncoding)!)
 print("Upload Video File3")
postData.appendData(NSData(data: data!))
 print("Upload Video File4")
postData.appendData("\r\n--\(boundary)--\r\n".dataUsingEncoding(NSUTF8StringEncoding)!)
print("Upload Video File5")
request.HTTPBody = postData

print("Upload Video File6")

print(request.HTTPBody)
NSURLConnection.sendAsynchronousRequest(request, queue: NSOperationQueue(), completionHandler:{ (response: NSURLResponse?, data: NSData?, error: NSError?) -> Void in
    let error: AutoreleasingUnsafeMutablePointer<NSError?> = nil
    do{
        if let jsonResult: NSDictionary! = try NSJSONSerialization.JSONObjectWithData(data!, options:NSJSONReadingOptions.MutableContainers) as? NSDictionary{


    }
    } catch let error as NSError {
    print(error.localizedDescription)
    }


})
 }

我在下面提到了两个链接但对我没用。

1)Imageor-video-posting-to-server-in-swift
2)how-to-upload-video-to-server-from-iphone

3 个答案:

答案 0 :(得分:5)

将代码更新为swift 4.2

试试这个。 它对我有用。

首先定义URL var。

using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Windows.Forms;
using System.Data.SqlClient;

namespace InventoryManager
{
    public partial class frmLogin : Form
    {
        public frmLogin()
        {
            InitializeComponent();
        }

        private void frmLogin_Load(object sender, EventArgs e)
        {
            this.AcceptButton = btnSubmit;
        }

        string cs = @"Data Source= (LocalDB)\v11.0;AttachDbFilename=|DataDirectory|Users.mdf;Integrated Security = True;";

        private void btnSubmit_Click(object sender, EventArgs e)
        {
            if (txtUserID.Text == "" || txtPassword.Text == "")
            {
                MessageBox.Show("Please enter a User ID and Password");
                return;
            }

            try
            {
                SqlConnection con = new SqlConnection(cs);
                SqlCommand cmd = new SqlCommand("SELECT * FROM tbl_Login WHERE UserID = @userid AND Password = @password", con);
                cmd.Parameters.AddWithValue("@userid", txtUserID.Text);
                cmd.Parameters.AddWithValue("@password", txtPassword.Text);
                con.Open();
                SqlDataAdapter adapt = new SqlDataAdapter(cmd);
                DataSet ds = new DataSet();
                adapt.Fill(ds);
                con.Close();
                int count = ds.Tables[0].Rows.Count;

                if (count == 1)
                {
                    MessageBox.Show("Login Successful!");
                    this.Hide();
                    frmOverview fo = new frmOverview();
                    fo.Show();
                }

                else
                {
                    MessageBox.Show("Login Failed");
                    txtPassword.Text = "";
                }
            }

            catch (Exception ex)
            {
                MessageBox.Show(ex.Message);
            }
        }
    }
}

然后使用UIImagePickerControllerDelegate获取文件信息。

var videoPath: URL?

这是上传事件方法:

extension ViewController: UIImagePickerControllerDelegate {
    func imagePickerController(_ picker: UIImagePickerController, didFinishPickingMediaWithInfo info: [UIImagePickerController.InfoKey : Any]) {
        if let videoURL = info[UIImagePickerController.InfoKey.mediaURL] as? URL {
            print(videoURL)
        }
        self.dismiss(animated: true, completion: nil)
    }
}

答案 1 :(得分:2)

简单的方法是使用Alamofire上传文件。

首先使用cocoapods安装Alamofire

将其包含在您的pod文件中

pod'Alamofire','〜&gt; 4.0'

然后转到终端并将ddirectory更改为您的项目并输入

pod install

现在

导入Alamofire

现在您已获得要上传到服务器的视频路径

 func imagePickerController(_ picker: UIImagePickerController,didFinishPickingMediaWithInfo info: [String : Any])                       

 {   


   if let videoUrl = info[UIImagePickerControllerMediaURL] as? URL


  { 

    Alamofire.upload(multipartFormData: { (multipartFormData) in

            multipartFormData.append(videoUrl, withName: "Video")

        }, to:"http://yourserverpath.php")
        { (result) in
            switch result {
            case .success(let upload, _ , _):

                upload.uploadProgress(closure: { (progress) in

                    print("uploding")
                })

                upload.responseJSON { response in

                   print("done")

                }

            case .failure(let encodingError):
                print("failed")
                print(encodingError)

            }
        }



    self.dismiss(animated: true, completion: nil)
    }



}

这是php代码

 <?php

 $imgname=$_FILES['video']['name'];
 $imgloc=$_FILES['video']['tmp_name'];
 if(move_uploaded_file($imgloc,"upload/".$imgname)){
    echo "success";
 }
 else{
echo "failed";
 }


 ?>

答案 2 :(得分:0)

使用Alamofire 5,您可以执行以下操作将视频上传到服务器:

 import Alamofire

 func uploadVideo(videoUrl: URL) { // local video file path..
        let timestamp = NSDate().timeIntervalSince1970 // just for some random name.

        AF.upload(multipartFormData: { (multipartFormData) in
            multipartFormData.append(videoUrl, withName: "image", fileName: "\(timestamp).mp4", mimeType: "\(timestamp)/mp4")
        }, to: endPoint!  ).responseJSON { (response) in
            debugPrint(response)
        }
    }
  

注意:endPoint是一个字符串。示例:http://172.10.3.7:5000/uploadvideo