php - 使用纯 Swift、PHP 代码将视频上传到服务器

标签 php ios iphone swift

我正在尝试将视频上传到 Godaddy 服务器 使用 Swift 和 PHP。我可以将“2 秒”视频发送到文件管理器,但如果时间超过,就会失败。

    // This function combining the unquie ID and the string -VIDEO.mov to make a file name for the  body.appendString in cresteBodyWithPramsVideo function.
func videoID () -> String{
    let unquieID =  theDictionary.value(forKey: "unquieID") as! String
    let filename = "-VIDEO.mov"
    let filename2 = "\(unquieID)" + "\(filename)"
    return filename2
}



func createBodyWithParamsVideo(_ parameters: [String: String]?, filePathKey: String?, imageDataKey: Data, boundary: String) -> Data {

    let body = NSMutableData();

    if parameters != nil {
        for (key, value) in parameters! {
            body.appendString(string: "--\(boundary)\r\n")
            body.appendString(string: "Content-Disposition: form-data; name=\"\(key)\"\r\n\r\n")
            body.appendString(string: "\(value)\r\n")
        }
    }


    let mimetype = "video/mov"

    body.appendString(string: "--\(boundary)\r\n")
    body.appendString(string: "Content-Disposition: form-data; name=\"\(filePathKey!)\"; filename=\"\(videoID())\"\r\n")
    body.appendString(string: "Content-Type: \(mimetype)\r\n\r\n")
    body.append(imageDataKey)
    body.appendString(string: "\r\n")
    body.appendString(string: "--\(boundary)--\r\n")

    return body as Data

}




func uploadVideo (){

    let unquieID  =  theDictionary.value(forKey: "unquieID") as! String

    // url path to php file
    let url = URL(string: "http://www.myWebSite.com/Video.php")!

    // declare request to this file
    var request = URLRequest(url: url)

    // declare method 
    request.httpMethod = "POST"

    // param to be sent in body of request
    let param = ["id" : unquieID]

    // body
    let boundary = "Boundary-\(UUID().uuidString)"
    request.setValue("multipart/form-data; boundary=\(boundary)", forHTTPHeaderField: "Content-Type")

    // Issign video to videoData var
    let videoData = theDictionary.value(forKey: "theVideo") as! NSData

    // ... body
    request.httpBody = createBodyWithParamsVideo(param, filePathKey: "file", imageDataKey: videoData as Data, boundary: boundary)

    // launch session
    URLSession.shared.dataTask(with: request) { data, response, error in
        if let response = response {
        }

        // get main queue to communicate back to user
        DispatchQueue.main.async(execute: {


            if error == nil {

                do {
                    // json containes $returnArray from php
                    let json = try JSONSerialization.jsonObject(with: data!, options: .allowFragments) as? NSDictionary
                    print(data!)
                    print(json!)

                    // declare new parseJSON to store json
                    guard let parseJSON = json else {
                        print("Error while parsing")

                        return
                    }

                    // get id from $returnArray["id"] - parseJSON["id"]
                    let id = parseJSON["id"]

                    // successfully uploaded
           if id != nil { 
           UserDefaults.standard.set(parseJSON, forKey: "parseJSON")
                    // unquieID = UserDefaults.standard.value(forKey: "parseJSON") as? NSDictionary

                        // did not give back "id" value from server
                    } else {
                       //Do somthing
                        // get main queue to communicate back to user
                        // DispatchQueue.main.async(execute: {
                        // let message = parseJSON["message"] as! String
                        // appDelegate.infoView(message: message, color: colorSmoothRed)
                        //                        })

                    }

                    // error while jsoning
                } catch {

                    // get main queue to communicate back to user
                    //  DispatchQueue.main.async(execute: {
                    ////  let message = error as! String

                    // appDelegate.infoView(message: message, color: colorSmoothRed)
                    //         })
                    //                   return
                }


                // error with php
            } else {

                // get main queue to communicate back to user
                // DispatchQueue.main.async(execute: {
                ////   let message = error!.localizedDescription
                print("message")
                // appDelegate.infoView(message: message, color: colorSmoothRed)
                //       })
                // return
            }


        })

        }.resume()

}

//Creating protocol of appending string to var of type data
extension NSMutableData {
func appendString(string : String) {
    let data = string.data(using: String.Encoding.utf8,    allowLossyConversion: true)
        append(data!)
    }
}

PHP

<?php


//STEP 1. Check passed data to this php file
if (empty($_REQUEST['id'])) {
$returnArray["massage"] = "Missing required information";
return;
}


// Pass POST via htmlencryot and assign to $id
$id = htmlentities($_REQUEST['id']);



//STEP 2. Folder for uploaded Video.
$folder = "VBCVideo/";



//STEP 3. Move uploaded file
$folder = $folder . basename($_FILES["file"]["name"]);

if (move_uploaded_file($_FILES["file"]["tmp_name"], $folder)) {
    $returnArray["status"] = "200";
    $returnArray["massage"] = "The Video file has been uploaded";
} else {
    $returnArray["status"] = "300";
    $returnArray["massage"] = "Error while uploading the Video";
}


// STEP 8. Feedback array to app user
echo json_encode($returnArray);

?>

现在 Godaddy PHP.ini upload_max_filesize 已更正“请参阅下面的评论”,问题大致相同。我现在可以上传一个长达 12 秒的文件,任何更长的文件都不会上传。我该去哪里?

最佳答案

我必须将 PHP.ini 文件添加到 public_html 下的 Godaddy FileDirector。转到“+文件”创建一个新文件并将其命名为“php.ini”

将这些行添加到文件中并保存。

最大执行时间=120;

upload_max 文件大小 = 60M;

post_max_size = 70M;

关于php - 使用纯 Swift、PHP 代码将视频上传到服务器,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/44664877/

相关文章:

php - 如何在 jquery 中发出警报,以了解要添加的事件是否已在数据库中或与其他事件的时间表冲突?

html - 在网络上定位使用 ios 5 的用户

ios - Storyboard中 View Controller 之间的共享实例

ios - Swift URL查询字符串获取参数

iphone - 未声明 - 'first use in function'

php - 函数打印但不适用于数组

php - 如何在 JavaScript 中使用 PHP 变量值?

iphone - CAAnimations,并更新图层树

iphone - iOS 添加对象到 NSDictionary 并访问 NSDictionary 中的对象

php - MySql 变量和 php