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)\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")
}
}
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.
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
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)\r\n".dataUsingEncoding(NSUTF8StringEncoding)!)
let fileNameContentDisposition = "name=\(fileName)"
let contentDisposition = "Content-Disposition: form-data; name=\"\(fileName)\"; \(imageData)\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
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()
Related
I have an IOS app that uses PHP for my API. My file upload is working fine but the name of the file is not appending to the file. I've mirrored other pages in my app but it's still not working although others are working fine. I’m able to see the file on the server, but the name is notes-.jpg. It’s not appending the puuid to the name per the code. I've implemented MessageKit on the ViewController that isn't working (just in case it makes a difference). Here is my code below, I feel like I'm looking for a needle in a haystack. The code is a little sloppy (please don't judge).
func createBodyWithParams(_ parameters: [String: String]?, filePathKey: String?, imageDataKey: Data, boundary: String) -> Data {
let 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")
body.appendString("\(value)\r\n")
}
}
// if file is not selected, it will not upload a file to server, because we did not declare a name file
var filename = ""
if imageSelected == true {
filename = "notes-\(puuid).jpg"
print("name of file", filename)
}
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.append(imageDataKey)
body.appendString("\r\n")
body.appendString("--\(boundary)--\r\n")
return body as Data
}
func uploadImage(_ image: UIImage, completion: #escaping (URL?) -> Void) {
print("im in upload")
let avame = user!["ava"]
let user_id = user!["id"] as! String
let me = user!["username"] as! String
let recipientfe = getmessages["recipient"]
let uuidfe = getmessages["uuid"] as! String
let recipient = getmessages["username"] as! String
let rid = String(describing: getmessages["sender_id"]!)
let puuid = UUID().uuidString
let text = ""
let url = URL(string: "https://localhost/messagepost.php")!
var request = URLRequest(url: url)
request.httpMethod = "POST"
let parameters = ["sender_id": user_id, "uuid": uuidfe, "sender": me, "recipient_id": rid, "recipient": recipient, "puuid": puuid, "text": text]
let boundary = "Boundary-\(UUID().uuidString)"
request.setValue("multipart/form-data; boundary=\(boundary)", forHTTPHeaderField: "Content-Type")
var data = Data()
if image != nil {
data = image.jpegData(compressionQuality: 0.5)!
}
request.httpBody = createBodyWithParams(parameters, filePathKey: "file", imageDataKey: data, boundary: boundary)
URLSession.shared.dataTask(with: request) { data, response, error in
DispatchQueue.main.async(execute: {
if error != nil {
Helper().showAlert(title: "Server Error", message: error!.localizedDescription, in: self)
print("Server Error")
return
}
do {
guard let data = data else {
Helper().showAlert(title: "Data Error", message: error!.localizedDescription, in: self)
print("Data Error")
return
}
let json = try JSONSerialization.jsonObject(with: data, options: .allowFragments) as? NSDictionary
guard let parsedJSON = json else {
return
}
if parsedJSON["status"] as! String == "200" {
let newurl = parsedJSON["path"]
self.isSendingPhoto = true
guard let url = newurl else {
return
}
var message = Message(messageuser: self.sender, image: image)
message.downloadURL = url as? URL
self.save(message)
self.messagesCollectionView.scrollToBottom()
} else {
if parsedJSON["message"] != nil {
let message = parsedJSON["message"] as! String
Helper().showAlert(title: "Error", message: message, in: self)
print("where am i", parsedJSON["message"] as Any)
}
}
} catch {
Helper().showAlert(title: "JSON Error", message: error.localizedDescription, in: self)
print("where am i 2")
}
})
}.resume()
}
PHP Upload File
<?php
if (!empty($_REQUEST["uuid"])) {
$id = htmlentities($_REQUEST["id"]);
$recipient = htmlentities($_REQUEST["recipient"]);
$recipient_id = htmlentities($_REQUEST["recipient_id"]);
$uuid = htmlentities($_REQUEST["uuid"]);
$puuid = htmlentities($_REQUEST["puuid"]);
$text = htmlentities($_REQUEST["text"]);
$sender = htmlentities($_REQUEST["sender"]);
$sender_id = htmlentities($_REQUEST["sender_id"]);
if (isset($_FILES['file']) && $_FILES['file']['size'] > 1) {
$folder = "/home/xxxxx/public_html/notes/" . $uuid;
// if no posts folder, create it
if (!file_exists($folder)) {
mkdir($folder, 0777, true);
}
$picture = $folder . "/" . basename($_FILES["file"]["name"]);
chmod($picture,0777);
if (move_uploaded_file($_FILES["file"]["tmp_name"], $picture)) {
$path = "http://localhost/notes/" . $uuid . "/notes-" . $puuid . ".jpg";
$returnArray["message"] = "Post has been made with picture";
$returnArray["path"] = $path;
$returnArray["status"] = "200";
} else {
$returnArray["message"] = "Post has been made without picture";
$path = "";
}
$result=$access->insertMessage($recipient, $recipient_id, $uuid, $sender,$sender_id, $text, $path);
// STEP 2.5 If posts are found, append them to $returnArray
if (!empty($result)) {
$returnArray["message"] = $result;
$result = $access->updatebadge($recipient_id);
}
else {
$returnArray["message"] = "Couldnt insert". $puuid ."";
}
// if data is not passed - show posts except id of the user
}
else {
$username = htmlentities($_REQUEST["username"]);
$uuid = htmlentities($_REQUEST["uuid"]);
$recipient_id = htmlentities($_REQUEST["recipient_id"]);
$message = $access->conversation($username, $uuid, $recipient_id);
if (!empty($message)) {
$returnArray["message"] = $message;
}
}
}
$access->disconnect();
echo json_encode($returnArray);
?>
I figured it out. The body and headers in Swift were incorrect and weren't sending the correct file name.
I changed the body to:
// web development and MIME Type of passing information to the web server
let boundary = "Boundary-\(NSUUID().uuidString)"
request.setValue("multipart/form-data; boundary=\(boundary)", forHTTPHeaderField: "Content-Type")
// access / convert image to Data for sending to the server
var data = Data()
// if picture has been selected, compress the picture before sending to the server
if image != nil {
data = image.jpegData(compressionQuality: 0.5)!
}
// building the full body along with the string, text, file parameters
request.httpBody = Helper().body(with: parameters, filename: "notes-\(puuid).jpg", filePathKey: "file", imageDataKey: data, boundary: boundary) as Data
I am trying to use Google Vision API and upload an image using their API to get analysis. I am using this php code:
<?php
include("./includes/common.php");
include_once("creds.php"); // Get $api_key
$cvurl = "https://vision.googleapis.com/v1/images:annotate?key=" . $api_key;
$type = "LABEL_DETECTION";
//echo "Item is: " . $item;
//Did they upload a file...
$item = $_GET[item];
if($_FILES['photo']['name'])
{
}else{
echo "you did not upload image".
}
It always show "you did not upload image". And here's my Swift function where I upload the image:
func UploadRequest(img: UIImage, item: String)
{
let url = NSURL(string: "http://myurlhere")
let request = NSMutableURLRequest(URL: url!)
request.HTTPMethod = "POST"
let boundary = generateBoundaryString()
//define the multipart request type
request.setValue("multipart/form-data; boundary=\(boundary)", forHTTPHeaderField: "Content-Type")
let image_data = UIImagePNGRepresentation(img)
if(image_data == nil)
{
return
}
let body = NSMutableData()
let fname = "image.png"
let mimetype = "image/png"
//define the data post parameter
body.appendData("--\(boundary)\r\n".dataUsingEncoding(NSUTF8StringEncoding)!)
body.appendData("Content-Disposition:form-data; name=\"test\"\r\n\r\n".dataUsingEncoding(NSUTF8StringEncoding)!)
body.appendData("hi\r\n".dataUsingEncoding(NSUTF8StringEncoding)!)
body.appendData("--\(boundary)\r\n".dataUsingEncoding(NSUTF8StringEncoding)!)
body.appendData("Content-Disposition:form-data; name=\"file\"; filename=\"\(fname)\"\r\n".dataUsingEncoding(NSUTF8StringEncoding)!)
body.appendData("Content-Type: \(mimetype)\r\n\r\n".dataUsingEncoding(NSUTF8StringEncoding)!)
body.appendData(image_data!)
body.appendData("\r\n".dataUsingEncoding(NSUTF8StringEncoding)!)
body.appendData("--\(boundary)--\r\n".dataUsingEncoding(NSUTF8StringEncoding)!)
request.HTTPBody = body
let session = NSURLSession.sharedSession()
let task = session.dataTaskWithRequest(request) {
(
let data, let response, let error) in
guard let _:NSData = data, let _:NSURLResponse = response where error == nil else {
//EZLoadingActivity.hide(success: false, animated: true)
print("error")
return
}
let dataString = NSString(data: data!, encoding: NSUTF8StringEncoding)
print(dataString)
//EZLoadingActivity.hide(success: true, animated: true)
self.dismissViewControllerAnimated(true, completion: nil)
}
task.resume()
}
When I do print_r($_FILES), I get:
Array
(
[file] => Array
(
[name] => image.png
[type] => image/png
[tmp_name] => /tmp/phplSB2dc
[error] => 0
[size] => 864781
)
)
Your form data is currently submitting:
body.appendData("Content-Disposition:form-data; name=\"file\";...
And according to your print_r($_FILES), you should be using file instead of photo:
$_FILES['file']['name']
Also, you should be checking to make sure the file uploaded correctly using:
if ( $_FILES['file']['error'] == UPLOAD_ERR_OK )
{
//File uploaded correctly
}
func uploadMultipleIMAGE( APIStriing:NSString, dataString:NSString) -> Void
{
//Here dataString is image binary data just append you your url and just pass the image it will handle.
print("wscall URL string \(APIStriing)")
print("Data string URL string \(dataString)")
let postData = dataString.dataUsingEncoding(NSASCIIStringEncoding, allowLossyConversion: true)!
let postLength = "\(UInt(postData.length))"
let request = NSMutableURLRequest()
request.URL = NSURL(string: APIStriing as String)!
request.HTTPMethod = "POST"
request.setValue(postLength, forHTTPHeaderField: "Content-Length")
request.setValue("application/x-www-form-urlencoded", forHTTPHeaderField: "Content-Type")
request.HTTPBody = postData
NSURLConnection.sendAsynchronousRequest(request, queue: NSOperationQueue.mainQueue(), completionHandler: {(response: NSURLResponse?,data: NSData?,error: NSError?) -> Void in
if error == nil {
print("success")
}
else {
let alert = UIAlertView(title: "Sorry For Inconvenience ", message: "Contact to Administration", delegate: self, cancelButtonTitle: "Ok")
alert.show()
}
})
}
Note:- when you convert image to binary data you need to handle special character. here you can handle special character. follow this step.
1.
let imgData = UIImagePNGRepresentation(image)
imgBase64String = imgData!.base64EncodedStringWithOptions(NSDataBase64EncodingOptions())
var newimagdat = NSString()
newimagdat = newimagdat.stringByAppendingString(self.percentEscapeString(imgBase64String) as String)
imgarray.addObject(newimagdat)
Create character handler class something like that.
class handlecharacter: NSCharacterSet {
func urlParameterValueCharacterSet() -> NSCharacterSet {
let characterser = NSMutableCharacterSet.alphanumericCharacterSet()
characterser.addCharactersInString("-._~")
return characterser
}
}
Now create function your class where you want to upload images
func percentEscapeString(imgstring:NSString) -> NSString
{
let handle = handlecharacter()
return imgstring.stringByAddingPercentEncodingWithAllowedCharacters(handle.urlParameterValueCharacterSet())!
}
I am writ plugin for WordPress. It sends a link to the images on the PHP file (Ajax).
The array consists of 10 photos.
obj.photos.push({ img_url: img_url, source: source, photo_text: photo_text, tag: tag });
var data_insert = {
action: 'instapin_insert',
data: obj
};
$.ajax({
type: 'POST',
url: '/wp-content/plugins/instapin/ajax.php',
data: data_insert,
});
Next, the file takes a picture and the script loads to the cloud with Google (Google Drive).
<?php
session_start();
session_write_close();
require_once('../../../wp-config.php');
global $service;
if(class_exists('INSTAPIN'))
{
$instapin = new INSTAPIN();
}
$google_drive = get_option('instapin_drive');
$photos_array = $_POST['data']['photos'];
// Создаём объект записи
$instapin_post = array(
'post_title' => 'Название записи',
'post_content' => '',
'post_status' => 'draft',
'post_author' => 1,
'post_category' => array(0)
);
// Вставляем запись в базу данных
$post_id = wp_insert_post( $instapin_post );
if($google_drive == 'on'){
$folder = get_option('google_upload_folder');
$found = false;
$files = $service->files->listFiles();
foreach ($files['items'] as $item) {
if ($item['title'] == $post_id) {
$folder_insert_photo = $item['id'];
$found = true;
break;
}
}
if($found == false){
$file = new Google_Service_Drive_DriveFile();
//Setup the Folder to Create
$file->setTitle($post_id);
$file->setDescription('Photo folder: post_id - ' . $post_id);
$file->setMimeType('application/vnd.google-apps.folder');
//Set the ProjectsFolder Parent
$parent = new Google_Service_Drive_ParentReference();
$parent->setId( $folder );
$file->setParents(array($parent));
//create the ProjectFolder in the Parent
$createdFile = $service->files->insert($file, array(
'mimeType' => 'application/vnd.google-apps.folder',
));
$folder_insert_photo = $createdFile->id;
$instapin->insertPermission($service, $folder_insert_photo, 'id', 'anyone', 'reader');
}
$count = 1;
$photo = new Google_Service_Drive_DriveFile();
$parent_folder = new Google_Service_Drive_ParentReference();
foreach($photos_array as $item){
if($count == 40){
break;
}
$img_url = strtok($item['img_url'], '?');
$image_url = str_replace("s150x150/", "", $img_url);
$image_data = file_get_contents($image_url); // Get image data
$filename = basename($image_url); // Create image file name
$wp_filetype = wp_check_filetype( $filename, null );
$MimeType = $wp_filetype['type'];
$seo_name = $item['tag'] . '_' . $count . '.jpg';
//Setup the Folder to Create
$photo->setTitle($seo_name);
$photo->setDescription('Photo: ' . $image_url);
$photo->setMimeType($MimeType);
$parent_folder->setId( $folder_insert_photo );
$photo->setParents(array($parent_folder));
// Try to upload the file, you can add the parameters e.g. if you want to convert a .doc to editable google format, add 'convert' = 'true'
$createdPhoto = $service->files->insert($photo, array(
'data' => $image_data,
'mimeType' => $MimeType,
'uploadType'=> 'multipart'
));
$instapin->insertPermission($service, $createdPhoto->id, 'id', 'anyone', 'reader');
$filePath = "GoogleDrive/{$folder_insert_photo}/{$seo_name}";
$fullFile = "https://googledrive.com/host/{$folder_insert_photo}/{$seo_name}";
print_r($fullFile);
$count++;
}
}
?>
But when I send an AJAX post to upload 10 photos, all admin panel and front. Nothing can be done and go until the download is complete (the script works).
But when I post to download 10 photos, all admin panel and front crashes (hangs). Nothing can be done and go until the upload is finished (the script works).
How to make this multi-tasking? So the admin panel and front continue to work, and the script is working in the background.
I'm creating an iOS application using AFMultipartFormData AFNetworking to upload an image onto Wordpress site. On the Wordpress server side, the following data was received when I echoed $_FILES:
media = {
error = (
0
);
name = (
"IMG_0004.JPG"
);
"tmp_name" = (
"C:\\Windows\\Temp\\phpF010.tmp"
);
type = (
"image/jpeg"
);
};
Somehow, Wordpress doesn't recognize my file as a valid image file in wp_check_filetype_and_ext() as I'm getting the following error back:
Error Domain=com.alamofire.error.serialization.response Code=-1011 "Request failed: unsupported media type (415)"
Here is my Wordpress function to handle the file uploaded and insert it into the media directory:
function ldp_image_upload( $request ) {
if ( empty($_FILES) ) {
return new WP_Error( 'Bad Request', 'Missing media file', array( 'status' => 400 ) );
}
$overrides = array('test_form' => false);
$uploaded_file = $_FILES['media'];
$wp_filetype = wp_check_filetype_and_ext( $uploaded_file['tmp_name'], $uploaded_file['name'] );
if ( ! wp_match_mime_types( 'image', $wp_filetype['type'] ) )
return new WP_Error( 'Unsupported Media Type', 'Invalid image file', array( 'status' => 415 ) );
$file = wp_handle_upload($uploaded_file, $overrides);
if ( isset($file['error']) )
return new WP_Error( 'Internal Server Error', 'Image upload error', array( 'status' => 500 ) );
$url = $file['url'];
$type = $file['type'];
$file = $file['file'];
$filename = basename($file);
// Construct the object array
$object = array(
'post_title' => $filename,
'post_content' => $url,
'post_mime_type' => $type,
'guid' => $url,
);
// Save the data
$id = wp_insert_attachment($object, $file);
if ( !is_wp_error($id) ) {
// Add the meta-data such as thumbnail
wp_update_attachment_metadata( $id, wp_generate_attachment_metadata( $id, $file ) );
}
// Create the response object
$response = new WP_REST_Response( array('result' => 'OK'));
return $response;
}
Here is the code on the front-end to send the image:
- (void)createMedia:(RemoteMedia *)media
forBlogID:(NSNumber *)blogID
progress:(NSProgress **)progress
success:(void (^)(RemoteMedia *remoteMedia))success
failure:(void (^)(NSError *error))failure
{
NSProgress *localProgress = [NSProgress progressWithTotalUnitCount:2];
NSString *path = media.localURL;
NSString *type = media.mimeType;
NSString *filename = media.file;
NSString *apiPath = [NSString stringWithFormat:#"sites/%#/media/new", blogID];
NSString *requestUrl = [self pathForEndpoint:apiPath
withVersion:ServiceRemoteRESTApibbPressExtVersion_1_0];
NSMutableURLRequest *request = [self.api.requestSerializer multipartFormRequestWithMethod:#"POST"
URLString:[[NSURL URLWithString:requestUrl relativeToURL:self.api.baseURL] absoluteString]
parameters:nil
constructingBodyWithBlock:^(id<AFMultipartFormData> formData) {
NSURL *url = [[NSURL alloc] initFileURLWithPath:path];
[formData appendPartWithFileURL:url name:#"media[]" fileName:filename mimeType:type error:nil];
} error:nil];
AFHTTPRequestOperation *operation = [self.api HTTPRequestOperationWithRequest:request success:^(AFHTTPRequestOperation * operation, id responseObject) {
NSDictionary *response = (NSDictionary *)responseObject;
NSArray * errorList = response[#"error"];
NSArray * mediaList = response[#"media"];
if (mediaList.count > 0){
RemoteMedia * remoteMedia = [self remoteMediaFromJSONDictionary:mediaList[0]];
if (success) {
success(remoteMedia);
}
localProgress.completedUnitCount=localProgress.totalUnitCount;
} else {
DDLogDebug(#"Error uploading file: %#", errorList);
localProgress.totalUnitCount=0;
localProgress.completedUnitCount=0;
NSError * error = nil;
if (errorList.count > 0){
NSDictionary * errorDictionary = #{NSLocalizedDescriptionKey: errorList[0]};
error = [NSError errorWithDomain:WordPressRestApiErrorDomain code:WPRestErrorCodeMediaNew userInfo:errorDictionary];
}
if (failure) {
failure(error);
}
}
} failure:^(AFHTTPRequestOperation *operation, NSError *error) {
DDLogDebug(#"Error uploading file: %#", [error localizedDescription]);
localProgress.totalUnitCount=0;
localProgress.completedUnitCount=0;
if (failure) {
failure(error);
}
}];
// Setup progress object
[operation setUploadProgressBlock:^(NSUInteger bytesWritten, long long totalBytesWritten, long long totalBytesExpectedToWrite) {
localProgress.completedUnitCount +=bytesWritten;
}];
unsigned long long size = [[request valueForHTTPHeaderField:#"Content-Length"] longLongValue];
// Adding some extra time because after the upload is done the backend takes some time to process the data sent
localProgress.totalUnitCount = size+1;
localProgress.cancellable = YES;
localProgress.pausable = NO;
localProgress.cancellationHandler = ^(){
[operation cancel];
};
if (progress) {
*progress = localProgress;
}
[self.api.operationQueue addOperation:operation];
}
As far as the mimes type is concern, image/jpeg should be supported by wordpress. Unless C:\\Windows\\Temp\\phpF010.tmp is not a true image, then AFNetworking is sending a corrupted file?
Can anyone offer advice on this? Thanks in advance.
Does $wp_filetype['proper_filename'] return something? I haven't tried this but I think this should return the filename as it should be (i.e. with an extension). If it does, you should move the uploaded file to another location and then rename it with the new filename, the upload should then succeed.
i have a problem with my php file.
I'm trying to upload an image through xcode to mysql db.
here's swift code
let image = UIImage(named: "image.jpg")
var imageData = UIImageJPEGRepresentation(image, 1)
if imageData != nil{
var request = NSMutableURLRequest(URL: NSURL(string:"link php file")!)
var session = NSURLSession.sharedSession()
request.HTTPMethod = "POST"
var boundary = NSString(format: "---------------------------14737809831466499882746641449")
var contentType = NSString(format: "multipart/form-data; boundary=%#",boundary)
request.addValue(contentType, forHTTPHeaderField: "Content-Type")
var body = NSMutableData.alloc()
// Image
body.appendData(NSString(format: "--%#\r\n", boundary).dataUsingEncoding(NSUTF8StringEncoding)!)
body.appendData(NSString(format:"Content-Disposition: attachment; name=\"userfile\"; filename=\"img.jpg\"").dataUsingEncoding(NSUTF8StringEncoding)!)
//body.appendData(NSString(format: "Content-Type: application/octet-stream\r\n\r\n").dataUsingEncoding(NSUTF8StringEncoding)!)
body.appendData(imageData)
body.appendData(NSString(format: "\r\n--%#--\r\n", boundary).dataUsingEncoding(NSUTF8StringEncoding)!)
request.HTTPBody = body
var returnData = NSURLConnection.sendSynchronousRequest(request, returningResponse: nil, error: nil)
var returnString = NSString(data: returnData!, encoding: NSUTF8StringEncoding)
println("returnString \(returnString)")
}
and here's php code:
$myparam = $_FILES['userfile']; //getting image Here //getting textLabe Here
$target_path = "uploads/".basename($myparam['filename']);
if(move_uploaded_file($myparam['tmp_name'], $target_path)){
$var = 1;
}
else {
$var = 0;
}
$myarray = array("response" => $var, "path" => $target_path);
$out = json_encode($myarray);
echo($out);
the problem is in the path. it returns wrong path and so i found no image in "uploads" folder. if i change target_path in php file (for example $target_path = "uploads/image.jpg"), image is saved.
i think it's a very easy problem but i don't understand what i have to change.
thanks for any help
hi