gpt4 book ai didi

php - 用于将图像上传到 sftp 的特定 php 和 swift 代码

转载 作者:搜寻专家 更新时间:2023-11-01 05:41:08 24 4
gpt4 key购买 nike

php脚本和xcode显示这里是

****** response data =
Notice: Undefined index: userId in /home/raimonds/script.php on line 36
{"Message":"First name field empty","Status":"Error","userId":null}

所以这里是 php 代码:

<?php
if(!empty($_POST["firstName"])){

$firstName = isset($_POST["firstName"]) ? $_POST["firstName"] : "";
$lastName = isset($_POST["lastName"]) ? $_POST["lastName"] : "";
$userId = isset($_POST["userId"]) ? $_POST["userId"] : "";
$target_dir = "uploads/";

if(!file_exists($target_dir))
{
mkdir($target_dir, 0777, true);
}

$target_dir = $target_dir . "/" . basename($_FILES["file"]["name"]);

if (move_uploaded_file($_FILES["file"]["tmp_name"], $target_dir)) {
echo json_encode([
"Message" => "The file ". basename( $_FILES["file"]["name"]). " has been uploaded.",
"Status" => "OK",
"userId" => $_POST["userId"]
]);

} else {
echo json_encode([
"Message" => "Sorry, there was an error uploading your file.",
"Status" => "Error",
"userId" => $_POST["userId"]
]);
}

}else{

echo json_encode([
"Message" => "First name field empty",
"Status" => "Error",
"userId" => $_POST["userId"]
]);

}

?>

你能帮帮我吗? xcode 部分是:

//
// ViewController.swift
// ImageUploader
//
// Created by Raimonds on 14/05/15.
// Copyright (c) 2015 Raimonds. All rights reserved.
//

import UIKit

class ViewController: UIViewController, UIImagePickerControllerDelegate,
UINavigationControllerDelegate

{
@IBOutlet weak var myImageView: UIImageView!

@IBOutlet weak var myActivityIndicator: UIActivityIndicatorView!

override func viewDidLoad() {
super.viewDidLoad()
// Do any additional setup after loading the view, typically from a nib.
}

override func didReceiveMemoryWarning() {
super.didReceiveMemoryWarning()
// Dispose of any resources that can be recreated.
}


@IBAction func uploadButtonTapped(sender: AnyObject) {

myImageUploadRequest()

}

@IBAction func selectPhotoButtonTapped(sender: AnyObject) {

var myPickerController = UIImagePickerController()
myPickerController.delegate = self;
myPickerController.sourceType = UIImagePickerControllerSourceType.PhotoLibrary

self.presentViewController(myPickerController, animated: true, completion: nil)

}

func imagePickerController(picker: UIImagePickerController, didFinishPickingMediaWithInfo info: [NSObject : AnyObject])

{

myImageView.image = info[UIImagePickerControllerOriginalImage] as?
UIImage

self.dismissViewControllerAnimated(true, completion: nil)

}





func myImageUploadRequest()

{

let myUrl = NSURL(string: "http://raimonds.gtd.lv/script.php");
let request = NSMutableURLRequest(URL: myUrl!);
request.HTTPMethod = "POST";


let param = [
"firstName" : "firstName",
"lastName" : "lastName",
"userId" : "9"
]

let boundary = generateBoundaryString()

request.setValue("multipart/form-data: boundary=\(boundary)" , forHTTPHeaderField: "Content-Type")

let imageData = UIImageJPEGRepresentation(myImageView.image, 1)

if (imageData==nil) {return; }

request.HTTPBody = createBodyWithParameters(param, filePathKey: "file", imageDataKey: imageData, boundary: boundary)

myActivityIndicator.startAnimating();

let task = NSURLSession.sharedSession().dataTaskWithRequest(request) {
data, response, error in

if error != nil {
println("error=\(error)")
return
}


println("******* response = \(response)")

let responseString = NSString(data: data, encoding: NSUTF8StringEncoding)
println("****** response data = \(responseString!)")

var err: NSError?
var json = NSJSONSerialization.JSONObjectWithData(data, options: .MutableContainers, error: &err)
as? NSDictionary


dispatch_async(dispatch_get_main_queue(),{
self.myActivityIndicator.stopAnimating()
self.myImageView.image = nil;

});


}


task.resume()


}


func createBodyWithParameters(parameters: [String: String]?, filePathKey: String?, imageDataKey: NSData, boundary: String) -> NSData {

var body = NSMutableData();

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

}
}

let filename = "user-profile.jpg"

let mimetype = "image/jpg"

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

body.appendString("--\(boundary)--\r\n")

return body
}

func generateBoundaryString() -> String {
return "Boundary--\(NSUUID().UUIDString)"
}

}

extension NSMutableData {
func appendString(string: String) {
let data = string.dataUsingEncoding(NSUTF8StringEncoding, allowLossyConversion: true)
appendData(data!)
}




}

最佳答案

你的 swift 代码有一些问题,因为你没有将 POST 数据发送到 php

尝试查看如何发送 swift POST 请求: http://ios-blog.co.uk/tutorials/swift-how-to-send-a-post-request-to-a-php-script/

你需要这样的东西:

var url: NSURL = NSURL(string: "http://raimonds.gtd.lv/script.php")!
var request:NSMutableURLRequest = NSMutableURLRequest(URL:url)
request.HTTPMethod = "POST"
var bodyData = "firstName=firstName&lastName=lastName&userId=9"
request.HTTPBody = bodyData.dataUsingEncoding(NSUTF8StringEncoding);
NSURLConnection.sendAsynchronousRequest(request, queue: NSOperationQueue.mainQueue())
{
(response, data, error) in
println(response)

}

关于php - 用于将图像上传到 sftp 的特定 php 和 swift 代码,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/30258615/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com