我已经搜索了很长时间,但没有任何结果适合我。 我什至尝试过 Alamofire。 我正在尝试通过 PHP 将 iOS 应用程序 (Swift 2.0) 中的图像上传到 Wordpress Photo-Contest 插件。 PHP脚本也用于Wordpress网站上传图片。
这是 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;
}
}
?>
这是我在 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)\r\n".dataUsingEncoding(NSUTF8StringEncoding)!)
let fileNameContentDisposition = "photo-description=\(fileName)"
let contentDisposition = "Content-Disposition: form-data; contest-photo=\"\(parameterName)\"; \(fileNameContentDisposition)\r\n"
tempData.appendData(contentDisposition.dataUsingEncoding(NSUTF8StringEncoding)!)
tempData.appendData("Content-Type: \(mimeType)\r\n\r\n".dataUsingEncoding(NSUTF8StringEncoding)!)
tempData.appendData(imageData)
tempData.appendData("\r\n".dataUsingEncoding(NSUTF8StringEncoding)!)
body.appendData(tempData)
body.appendData("\r\n--\(boundary)--\r\n".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")
}
}
经过很多来回,我把代码弄乱了很多,还从其他人那里复制了一些我发现的代码,只是为了让它工作。 我确实在控制台中打印出“<>-Data”。 如果有任何帮助或提示,我将不胜感激。
最佳答案
在评论中讨论之后,您需要一个工作示例来将您的用户名值发布到服务器。 这是一个 Java REST Web 服务:
@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) + "";
}
这就是您在 swift 客户端中的调用方式:
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()
}
请注意,该脚本期望在 post 中具有值,因此您所做的是将用户名传递给 url,然后让您的 php 脚本在 post 变量中找到它。这就是为什么你在 php 脚本中得到 null 的原因。
在这个例子中,我试图从我的 swift 客户端发布两个变量 x 和 y 到我的 REST jersey 网络服务。
希望对你有帮助
关于php - 使用 Swift 2.0 将图像上传到 PHP,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/32830431/