使用Swift 2.0将图像上传到PHP

I've searched for a long time now and nothing works out for me. I've even tried Alamofire. I'm trying to upload an image in an iOS App (Swift 2.0) to a Wordpress Photo-Contest plugin through PHP. The PHP script is also used for the Wordpress website to upload images.

This is the PHP:

<?php
define('WP_USE_THEMES', false);
require_once("../../../../../wp-load.php");

    $username = $_POST["username"];

    $m = contest_upload_photo('contest-upload-photo', 'contest_upload_photo',username_exists($username ));


function contest_upload_photo($atts, $content = null,$user_ID=null) {

//Important variables 

if ($user_ID == null){
    die(); 
}

$html = '';//Inciate output string
$koncovky = array('jpg', 'jpeg', 'png', 'gif');

$number_images = get_user_meta($user_ID, 'contest_user_images', true);
if(empty($number_images)){$number_images=0;}


$error = array();
// Do some minor form validation to make sure there is content

$name = trim($_POST['photo-name']);
    /*if (empty($_POST['photo-title'])){
    $error['title'] = __('Please enter the photo title','photo-contest');
} else {
    $title = trim($_POST['photo-title']);  
}*/
//Check photo


if ($_FILES['contest-photo']['error'] == UPLOAD_ERR_NO_FILE){
    $error['photo'] = __('Please select the image','photo-contest');
} else {

  //Control upload and extension
  if ($_FILES['contest-photo']['error']) {
    $error['upload_error'] = __('Error image upload.','photo-contest');
  } 
  elseif (!in_array(strtolower(pathinfo($_FILES['contest-photo']['name'], PATHINFO_EXTENSION)), $koncovky)) {
    $error['extension_error'] = __('Image must be jpg, png or gif.','photo-contest');
  } 
  elseif (!($imagesize = getimagesize($_FILES['contest-photo']['tmp_name'])) || $imagesize[2] > 3) {
    $error['type_error'] = __('Image type must be jpg, png or gif.','photo-contest');
  }   
  else {

    @$img=getimagesize($_FILES['contest-photo']['tmp_name']);

    $minimum = array('width' => '400', 'height' => '400');
    $width= $img[0];
    $height =$img[1];
      if ($width < $minimum['width'] ){
        $error['type_error'] = __('Minimum image width is 400px.','photo-contest');
      }
      elseif ($height <  $minimum['height']){
        $error['type_error'] = __('Minimum image height is 400px.','photo-contest');
      }
      $photo_limit = get_option( 'pcplugin-photo-limit', true );
      $size_maxi = $photo_limit;  
      $size = filesize($_FILES['contest-photo']['tmp_name']); 
      if($size>$size_maxi){  
        $error['size_error'] = __('File size is above allowed limitations!','photo-contest');  
}  
    }


}


if(empty($error)){
//If no exist error - create attachment post
  if(empty($_POST['photo-description'])){ 
    $description = sanitize_text_field($_POST['photo-description']);
  }else{
    $description = '';
  }

@$wp_filetype = wp_check_filetype(basename($_FILES['contest-photo']['name']), null );
@$wp_upload_dir = wp_upload_dir();
$attachment = array(
 'guid' => $wp_upload_dir['url'] . '/' . basename( $_FILES['contest-photo']['name'] ), 
 'post_mime_type' => $wp_filetype['type'],
 'post_title' => $name,
 'post_content' => $description,
 'post_status' => 'inherit'
);

require_once(ABSPATH . 'wp-admin/includes/image.php');
require_once(ABSPATH . "wp-admin" . '/includes/file.php');
require_once(ABSPATH . "wp-admin" . '/includes/media.php');
$attach_id = media_handle_upload( 'contest-photo', 0,$attachment );

$attach_data = wp_generate_attachment_metadata( $attach_id, $wp_upload_dir['url'] . '/' . basename( $_FILES['contest-photo']['name']) );

wp_update_attachment_metadata( $attach_id, $attach_data );

update_post_meta($attach_id,'contest-active',1);
update_post_meta($attach_id,'contest-photo-points',0);
update_post_meta($attach_id,'contest-photo-author',$user_ID);
    update_post_meta($attach_id,'post_author',$user_ID);

$number_images = $number_images+1;
update_user_meta($user_ID, 'contest_user_images', $number_images);


    $my_post = array(
  'ID'           => $attach_id,
  'post_author'   => $user_ID,
    );

    wp_update_post( $my_post );


    $image = get_post( $attach_id );

    if ($attach_id==""){
        die("306");
    }else{
        echo($attach_id); 
    }
    if ( ! $image || 'attachment' != $image->post_type || 'image/' != substr( $image->post_mime_type, 0, 6 ) )
        die( json_encode( array( 'error' => sprintf( __( 'Failed resize: %s is an invalid image ID.', 'regenerate-thumbnails' ), esc_html( $attach_id ) ) ) ) );



    $fullsizepath = get_attached_file( $image->ID );

    if ( false === $fullsizepath || ! file_exists( $fullsizepath ) )

    // @set_time_limit( 900 ); // 5 minutes per image should be PLENTY

    $metadata = wp_generate_attachment_metadata( $image->ID, $fullsizepath );

    if ( is_wp_error( $metadata ) )
    if ( empty( $metadata ) )
    wp_update_attachment_metadata( $image->ID, $metadata );
return $attach_id; 


}


}
    ?>

And this is my function in SWIFT:

func send()
{

    let imageData :NSData = UIImageJPEGRepresentation(globalImage, 1.0)!;
    var request: NSMutableURLRequest?
    let HTTPMethod: String = "POST"
    let timeoutInterval: NSTimeInterval = 60
    let HTTPShouldHandleCookies: Bool = false
    let postString = "username=\(globalUsr)"

    request = NSMutableURLRequest(URL: NSURL(string: "***URL TO upload.php***")!)
    request!.HTTPMethod = HTTPMethod
    request!.timeoutInterval = timeoutInterval
    request!.HTTPShouldHandleCookies = HTTPShouldHandleCookies
    request!.HTTPBody = postString.dataUsingEncoding(NSUTF8StringEncoding)


    let boundary = "----------SwIfTeRhTtPrEqUeStBoUnDaRy"
    let contentType = "multipart/form-data; boundary=\(boundary)"
    request!.setValue(contentType, forHTTPHeaderField:"Content-Type")
    let body = NSMutableData();


    let tempData = NSMutableData()
    let fileName = "\(globalImage.description).jpg"
    let parameterName = "contest-photo"


    let mimeType = "application/octet-stream"

    tempData.appendData("--\(boundary)
".dataUsingEncoding(NSUTF8StringEncoding)!)
    let fileNameContentDisposition = "photo-description=\(fileName)"
    let contentDisposition = "Content-Disposition: form-data; contest-photo=\"\(parameterName)\"; \(fileNameContentDisposition)
"
    tempData.appendData(contentDisposition.dataUsingEncoding(NSUTF8StringEncoding)!)
    tempData.appendData("Content-Type: \(mimeType)

".dataUsingEncoding(NSUTF8StringEncoding)!)
    tempData.appendData(imageData)
    tempData.appendData("
".dataUsingEncoding(NSUTF8StringEncoding)!)

    body.appendData(tempData)

    body.appendData("
--\(boundary)--
".dataUsingEncoding(NSUTF8StringEncoding)!)

    request!.setValue("\(body.length)", forHTTPHeaderField: "Content-Length")
    request!.HTTPBody = body

    do {
        let data = try NSURLConnection.sendSynchronousRequest(request!, returningResponse: nil)
        print("\(data)-Data")
    } catch (let vl_error) {
        print("\(vl_error)-Error")
    }


}

After a lot back and forth, I've messed up the code a lot and also copied some code from other people that I've found just to make it work. I do get "<>-Data" printed out in the console. I would appreciate any help or hint.

dscpg80066
dscpg80066 你有没有检查我的答案?
大约 5 年之前 回复
dtzhfb4869
dtzhfb4869 表示用户名在请求正文中。我会给你一个工作的例子:
大约 5 年之前 回复
douyan8070
douyan8070 我没有访问wordpress插件尝试了另一个脚本,这很好。有些东西似乎没有使用php,因为如果我在浏览器中使用?username=admin键入url并且我打印变量$username,它仍然是null。如果你能把工作实例寄给我,我将不胜感激。
大约 5 年之前 回复
dszpyf4859
dszpyf4859 我检查了你的代码,确实你正确地发送了用户名,但你说你正在寻找user_id而不是用户名。那是你的问题吗?另外,您确定您的Web服务接受了从swift发送的相同请求吗?如果你愿意,我可以给你一个客户端(swift)和服务器(javaREST服务)的工作示例
大约 5 年之前 回复
dpge74512
dpge74512 好的,我在php文件中内置了错误消息。请求以user_ID为空的错误消息消失,但我将用户名发送到php文件。你知道为什么会这样吗?
大约 5 年之前 回复
drsxzut183207938
drsxzut183207938 这意味着请求已成功发送。如果您正在服务器上获取请求正文,请检查。尝试在服务器中打印整个请求。对不起,我现在没有笔记本电脑
大约 5 年之前 回复
douba9654
douba9654 我也得到了这个:可选(<NSHTTPURLResponse:0x7fe961ec0200>{URL:url}{状态代码:200,headers{“Cache-Control”=“no-store,no-cache,must-revalidate,post-check=0,pre-check=0“;Connection=close;”Content-Length“=0;”Content-Type“=”text/html;charset=UTF-8“;Date=”Mon,28Sep201522:08:57GMT“;Expires=”Thu,1981年11月19日08:52:00GMT“;Pragma=”no-cache“;Server=”Apache/2.4.10“;”Set-Cookie“=”qtrans_cookie_test=1;path=/;domain=***domain***“;”X-Powered-By“=”PHP/5.6.12“;}})我已经替换了url和域名
大约 5 年之前 回复
dtg25862
dtg25862 必须有很多标题。请检查,特别是响应代码
大约 5 年之前 回复
duannaozhao4626
duannaozhao4626 如果我要求http响应头,控制台会打印出Optional()
大约 5 年之前 回复
douyu2817
douyu2817 我尝试了几个不同的脚本,也没有在wordpress上传文件。没有错误消息,在应用程序中我确实返回<>-数据。我几个星期以来只在Swift编程,所以我真的不知道从哪里开始。我正在考虑删除整个功能并创建一个新功能,但我不知道还有什么可行。
大约 5 年之前 回复
dopr25398
dopr25398 你可以打印http响应头吗?
大约 5 年之前 回复
doukeyong3746487
doukeyong3746487 我没有收到任何错误,文件没有上传,因此没有出现在网站上。
大约 5 年之前 回复
doukongpao0903
doukongpao0903 你做了什么调试?你怎么知道它不起作用?你从服务器的响应中得到了什么(你需要使用returnsResponse而不是传递nil来查找。)服务器错误日志中有什么?如果您使用API​​测试工具(Postman,Paw等)将图像发送到页面而不是Swift,会发生什么?
大约 5 年之前 回复
dsla94915
dsla94915 你有什么错误?你上传到休息网络服务?
大约 5 年之前 回复

2个回答



在评论中讨论后,您需要一个工作示例将您的用户名值发布到服务器。

这是一个java REST Web服务:</ p>

  @POST 
@ Produces(MediaType.TEXT_PLAIN)
@ Path(“/ swiftCalculator”)
public String swiftCalculator(@ FormParam(“x”)int x,@ FormParam(“y”)int y){
System.out.println(“x =”+ x);
System.out.println(“y =”+ y );
return(x + y)+“”;
}
</ code> </ pre>

这就是你从swift客户端调用它的方式:</ p>

  func testPost(sender:UIButton){
让session = NSURLSession.sharedSession()
让request = NSMutableURLRequest(URL:NSURL(string:“http:// localhost:8080 / iOSServer / ios / helloworld / swiftCalculator“)!)
request.HTTPMethod =”POST“
让d =”4“
让data =”x = 4&amp; y = \(d)“
request.HTTPBody = data.dataUsingEncoding(NSASCIIStringEncoding)
让task = session.dataTaskWithRequest(请求,completionHandler:{(数据,响应,错误)在
如果让错误=错误{
打印(错误)
}
如果让 data = data {
print(“data = \(data)”)
}
如果让response = response {
print(“response = \(response)”)
}
})
task.resume()\ n}
</ code> </ pre>

请注意,脚本期望在post中包含值,所以你要做的是将用户名传递给url,然后询问你的php脚本 在post变量中找到它。 这就是你在PHP脚本中得到null的原因。</ p>

在这个例子中,我试图发布</ strong>两个变量,这些变量是我的swift客户端的x和y 到我的REST球衣网络服务。</ p>

希望这有帮助</ p>
</ div>

展开原文

原文

After talking in comments, you needed a working example to post your username value to the server. This is a java REST web service:

@POST
@Produces(MediaType.TEXT_PLAIN)
@Path("/swiftCalculator")
public String swiftCalculator(@FormParam("x") int x, @FormParam("y") int y){
    System.out.println("x="+x);
    System.out.println("y="+y);
    return (x + y) + "";
}

And this is how you call it from your swift client:

 func testPost(sender: UIButton) {
        let session = NSURLSession.sharedSession()
        let request = NSMutableURLRequest(URL: NSURL(string: "http://localhost:8080/iOSServer/ios/helloworld/swiftCalculator")!)
        request.HTTPMethod = "POST"
        let d = "4"
        let data = "x=4&y=\(d)"
        request.HTTPBody = data.dataUsingEncoding(NSASCIIStringEncoding)
        let task = session.dataTaskWithRequest(request, completionHandler: {(data, response, error) in
            if let error = error {
                print(error)
            }
            if let data = data{
                print("data =\(data)")
            }
            if let response = response {
                print("response = \(response)")
            }
        })
        task.resume()
    }

Please notice that the script expects to have the values in post, so what you were doing is passing the username to the url and then ask your php script to find it in the post variables. that is why you were getting null in you php script.

In this example, i tried to post two variables, which are x and y from my swift client to my REST jersey web service.

Hope this helps



我已经调整了swift中的函数,到目前为止工作正常。
我只需要知道如何将文件上传到 PHP脚本,我尝试了不同的方法,但它现在给我一个错误,图像必须是jpg,png或gif。
Username,照片名称和描述被脚本接受。</ p>

  func send(){
let request = NSMutableURLRequest(URL:NSURL(string:“*** URL ***”)!)
request.HTTPMethod =“POST”
let postString =“username = \(globalUsr)&amp; photo-name = \(globalImage.description)&amp; photo-description = \(message.text)“

让myData:NSData! = postString.dataUsingEncoding(NSUTF8StringEncoding)

让imageData:NSData = UIImagePNGRepresentation(globalImage,1.0)!;

let boundary =“---------- SwIfTeRhTtPrEqUeStBoUnDaRy”
let contentType =“ multipart / form-data; boundary = \(boundary)“
let body = NSMutableData();

让tempData = NSMutableData()
让fileName =”\(globalImage.description).jpg“
let parameterName =“contest-photo”

让mimeType =“application / octet-stream”

tempData.appendData(myData)
tempData.appendData(“ - \(boundary)
“.dataUsingEncoding(NSUTF8StringEncoding)!)
让fileNameContentDisposition =”name = \(fileName)“
让contentDisposition =”Content-Disposition:form-data; name = \“\(fileName)\”; \(imageData)


\ tempData.appendData(contentDisposition.dataUsingEncoding(NSUTF8StringEncoding)!)
\ tempData.appendData(”Content-Type:\(mimeType)

“.dataUsingEncoding(NSUTF8StringEncoding)!)

tempData.appendData(imageData)
tempData.append 数据(“
”.dataUsingEncoding(NSUTF8StringEncoding)!)

body.appendData(tempData)

body.appendData(“

  • \ - (边界) -

“.dataUsingEncoding(NSUTF8StringEncoding)!)

request.setValue(”\(body.length)“,forHTTPHeaderField:”Content-Length“)
request.HTTPBody = body

let task = NSURLSession .sharedSession()。dataTaskWithRequest(request){
数据,响应,

中的错误如果错误!= nil {
print(“error = \(error)”)
返回
}
\ n让responseString = NSString(data:data!,encoding:NSUTF8StringEncoding)
print(“responseString = \(responseString!)”)
}
task.resume()
</ code> </ pre> \ n </ div>

展开原文

原文

I've adjusted the function in swift which works fine so far now. I only need to know how to upload a file to the php script, I've tried different approaches but it now gives me the error that the Image must be jpg, png or gif. Username, photo name and description get accepted by the script.

func send()  {
    let request = NSMutableURLRequest(URL: NSURL(string: "***URL***")!)
    request.HTTPMethod = "POST"
    let postString = "username=\(globalUsr)&photo-name=\(globalImage.description)&photo-description=\(message.text)"

    let myData : NSData! = postString.dataUsingEncoding(NSUTF8StringEncoding)

    let imageData :NSData = UIImagePNGRepresentation(globalImage, 1.0)!;

    let boundary = "----------SwIfTeRhTtPrEqUeStBoUnDaRy"
    let contentType = "multipart/form-data; boundary=\(boundary)"
    let body = NSMutableData();

    let tempData = NSMutableData()
    let fileName = "\(globalImage.description).jpg"
    let parameterName = "contest-photo"


    let mimeType = "application/octet-stream"

    tempData.appendData(myData)
    tempData.appendData("--\(boundary)
".dataUsingEncoding(NSUTF8StringEncoding)!)
    let fileNameContentDisposition = "name=\(fileName)"
    let contentDisposition = "Content-Disposition: form-data; name=\"\(fileName)\"; \(imageData)
"
    tempData.appendData(contentDisposition.dataUsingEncoding(NSUTF8StringEncoding)!)
    tempData.appendData("Content-Type: \(mimeType)

".dataUsingEncoding(NSUTF8StringEncoding)!)
    tempData.appendData(imageData)
    tempData.appendData("
".dataUsingEncoding(NSUTF8StringEncoding)!)


    body.appendData(tempData)

    body.appendData("
--\(boundary)--
".dataUsingEncoding(NSUTF8StringEncoding)!)

    request.setValue("\(body.length)", forHTTPHeaderField: "Content-Length")
    request.HTTPBody = body

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

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

        let responseString = NSString(data: data!, encoding: NSUTF8StringEncoding)
        print("responseString = \(responseString!)")
    }
    task.resume()

dro7152
dro7152 我在这里创建了一个新问题:stackoverflow.com/questions/32934329 / ...
大约 5 年之前 回复
dongsui5464
dongsui5464 如果您发布新问题,请给我链接。
大约 5 年之前 回复
douganggu4392
douganggu4392 现在你有另一个问题,如果我的答案可以帮助你,请接受它,然后开始一个表达你的新问题的新问题
大约 5 年之前 回复
Csdn user default icon
上传中...
上传图片
插入图片
抄袭、复制答案,以达到刷声望分或其他目的的行为,在CSDN问答是严格禁止的,一经发现立刻封号。是时候展现真正的技术了!
立即提问
相关内容推荐