Upload Image using Retrofit and PHP API - php

I am trying to upload image with Retrofit API. My android code is like below
public interface FileUploadService {
#Multipart
#POST("upload.php")
Single<ResponseBody> onFileUpload(#Part("username") RequestBody mUserName, #Part MultipartBody.Part file);
}
and PHP code is like below
<?php
$target_dir = "upload/";
$target_file_name = $target_dir .basename($_FILES["file"]["name"]);
$response = array();
// Check if image file is a actual image or fake image
if (isset($_FILES["file"]))
{
if (move_uploaded_file($_FILES["file"]["tmp_name"], $target_file_name))
{
$success = true;
$message = "Successfully Uploaded";
}
else
{
$success = false;
$message = "Error while uploading";
}
}
else
{
$success = false;
$message = "Required Field Missing";
}
$response["success"] = $success;
$response["message"] = $message;
echo json_encode($response);
?>
I am not getting any error in android side and its working fine but in server, I am getting error like below
PHP Notice: Undefined index: file in line 3
Let me know what I am missing. Thanks!

In your server part code, you're expecting the field name to be file. I guess that while preparing multipart data in Android, you're not using the same name (file).
In your Activity/Fragment, the multipart data preparation code should look like below.
String fileName = "your file name with extension";
RequestBody requestBody = RequestBody.create(MediaType.parse("multipart/form-data"), file);
MultipartBody.Part.createFormData("file", fileName, requestBody);
// ----^^^^--- look at the field name (first parameter)

Related

PHP move_uploaded_file fail

I am trying to upload an image through alamofire and I have done it! My server received it but when I call move_uploaded_file function in my php file it shows FAILURE. I am sure that my server received the image and i am able to create directories through php. It is just this move_uploaded_file not letting me do the job. Here is my php code:
<?php
if (empty($_FILES["image"])){
$response = array("error" => "no data");
}else{
$path = "./Upload";
if(!file_exists($path)){
mkdir($path,0777,true);
$response["message"] = "new file created";
}else{
$response["message"] = "file already exist";
if(move_uploaded_file($_FILES["image"]["tmp_name"],$path)){
$response["message"] = "You've got it!!!";
}else{
$response["message"] = "upload function fail";
}
}
}
echo json_encode($response);
?>
$path is a directory, not a file. Change it to:
$path = "./Upload/file.txt";
Change:
$path = "./Upload";
With:
$path= "uploads/" . basename($_FILES["fileToUpload"]["name"]);

Image Upload doesn't work with swift alamofire and php

After trying different approaches, I couldn't find the cause of the issue...
I'm trying to upload an image (choosen from photo library) to store it on a linux webserver using a php script.
Here the Swift 4 code:
func uploadImage(imageFile: UIImage?){
let imageData = UIImageJPEGRepresentation(imageFile!, 0.5)!
Alamofire.upload(
multipartFormData: { multipartFormData in
multipartFormData.append(imageData, withName: "image", fileName: "test", mimeType: "image/jpg")
},
to: "http://XXX/images/upload.php", method: .post,
encodingCompletion: { encodingResult in
switch encodingResult {
case .success(let upload, _, _):
upload.responseJSON { response in
if let result = response.result.value {
// Get the json response. From this, we can get all things we send back to the app.
//let JSON = result as! NSDictionary
//self.imageServerLocation = JSON.object(forKey: "filepath") as? String
debugPrint(response)
}
}
case .failure(let encodingError):
print(encodingError)
}
}
)
}
The code at the server where is the following:
<?php
if (empty($_FILES["image"])) {
// So we send a message back saying there is no data...
$response = array("error" => "nodata");
}else { // If there is data
$response['error'] = "NULL";
// Setup a filename for the file. Uniqid can be changed to anything, but this makes sure
// that every file doesn't overwrite anything existing.
$filename = uniqid() . ".jpg";
// If the server can move the temporary uploaded file to the server
if (move_uploaded_file($_FILES['image']['test'], '/default/' . $filename)) {
// Send a message back saying everything worked!
// I also send back a link to the file, and the name.
$response['status'] = "success";
$response['filepath'] = "https:" . $filename;
$response['filename'] = "".$_FILES["file"]["name"];
} else{
// If it can't do that, Send back a failure message, and everything there is / should be form the message
// Here you can also see how to reach induvidual data from the image, such as the name.
$response['status'] = "Failure";
$response['error'] = "".$_FILES["image"]["error"];
$response['name'] = "".$_FILES["image"]["name"];
$response['path'] = "".$_FILES["image"]["tmp_name"];
$response['type'] = "".$_FILES["image"]["type"];
$response['size'] = "".$_FILES["image"]["size"];
}
}
// Encode all the responses, and echo them.
// This way Alamofire gets everything it needs to know
echo json_encode($response);
?>
I get always the same error:
[Data]: 107 bytes
[Result]: SUCCESS: {
error = 0;
name = test;
path = "/tmp/php7iIqSv";
size = 43337;
status = Failure;
type = "image/jpg";
}
Can someone give me a hint to solve my problem?
Thanks in advance
I think you have error in move_uploaded_file function.You are giving key that is not there in $_FILES global
It should be like
move_uploaded_file($_FILES['image']['tmp_name'], '/default/' . $filename)
And make sure the folder/directory where you are moving the file is writable.

uploading file from android app into desired folder

I wan to upload file from android app using PHP in specific folder below is the code which I have tried.
pleas help me what is wrong in this code and please suggest me some easy solution for this or is this method right to upload files from android app on serever
$response = array();
if($_SERVER['REQUEST_METHOD']=='POST'){
//checking the required parameters from the request
if(isset($_POST['exp']) && isset($_POST['employee_id']) && isset($_FILES['pdf']['name']) ){
//connecting to the database
$con = mysqli_connect(DB_SERVER,DB_USER,DB_PASSWORD,DB_DATABASE) or die('Unable to Connect...');
$resume_name = $_POST['exp'];
$employee_id = $_POST['employee_id'];
$file_data = $_FILES['pdf']['name'];
$upload_path = 'Images/Employee_Profile_Picture/'.$employee_id.'/Resume/';
//getting file info from the request
$fileinfo = pathinfo($_FILES['pdf']['name']);
//getting the file extension
$extension = $fileinfo['extension'];
//file url to store in the database
$file_url = $upload_path . getFileName($employee_id). '.'. $extension;
//file path to upload in the server
$file_path = $upload_path . getFileName($employee_id);
try{
if(file_exists($upload_path))
{
$existing_file = glob($upload_path."/*.*");
$empty_file = implode(" ",$existing_file);
move_uploaded_file($_FILES['pdf']['name'],$upload_path) ;
$sql = "UPDATE employee_registration SET resume_name ='$resume_name', resume_path='$file_url' where employee_id ='$employee_id'";
//adding the path and name to database
if(mysqli_query($con,$sql)){
//filling response array with values
$response['Success'] = "File Uploaded Successfully...!";
echo json_encode($response);
}
else
{
$response['Error'] = "File Uploading Error...!";
echo json_encode($response);
}
}
else
{
mkdir('Images/Employee_Profile_Picture/'.$employee_id.'/Resume');
move_uploaded_file($_FILES['pdf']['name'],$upload_path) ;
$sql = "UPDATE employee_registration SET resume_name ='$resume_name', resume_path='$file_url' where employee_id ='$employee_id'";
//adding the path and name to database
if(mysqli_query($con,$sql))
{
//filling response array with values
$response['Success'] = "File Uploaded Successfully...!";
echo json_encode($response);
}
else
{
$response['Error'] = "File Uploading Error...!";
echo json_encode($response);
}
}
}catch(Exception $e){
$response['error']=true;
$response['message']=$e->getMessage();
}
}
}
//here is my method getFileName
function getFileName($employee_id)
{
//mysql query to fetch data
$sql = mysql_query("SELECT resume_path from employee_registration where
employee_id = '$employee_id'") or die(mysql_error());
while ($row = mysql_fetch_array($sql, MYSQL_ASSOC))
{
$response=$row['resume_path'];
}
$resume_name = explode("/", $response);
echo $resume_name[4];
return $resume_name;
}
Change below line:
move_uploaded_file($_FILES['pdf']['name'],$upload_path) ;
To
move_uploaded_file($_FILES['pdf']['tmp_name'],$upload_path) ;
tmp_name should be used to upload the file, as it has the full path of the file where it is temporarily stored. Where as the name contain only the name of file without any path information.
if this doenst work move_uploaded_file($_FILES['pdf']['tmp_name'],$upload_path) ;
kindly use this file_put_contents($upload_path,$_FILES['pdf']['tmp_name']);

Image Uploading from android application to Server is not working

I'm developing an android app which requires to upload the image taken with camera to the server. I used a tutorial for this and imported the project
from this link, refer this for android code
My PHP file which is indicating success of the image and returning me the URL but the image is not found on the server. I am not able to troubleshoot this problem.
My PHP file code is:
<?php
// Path to move uploaded files
$target_path = "Upload_image_ANDROID/";
// array for final json respone
$response = array();
// getting server ip address
$server_ip = '216.86.147.200';
// final file url that is being uploaded
$file_upload_url = 'http://' . $server_ip . '/' . 'sss_api' . '/' . $target_path;
if (isset($_FILES['image']['name'])) {
$target_path = $target_path . basename($_FILES['image']['name']);
// reading other post parameters
// $email = isset($_POST['email']) ? $_POST['email'] : '';
//$website = isset($_POST['website']) ? $_POST['website'] : '';
$response['file_name'] = basename($_FILES['image']['name']);
//$response['email'] = $email;
//$response['website'] = $website;
try {
// Throws exception incase file is not being moved
if (!move_uploaded_file($_FILES['image']['tmp_name'], $target_path)) {
// make error flag true
$response['error'] = true;
$response['message'] = 'Could not move the file!';
}
// File successfully uploaded
$response['message'] = 'File uploaded successfully!';
$response['error'] = false;
$response['file_path'] = $file_upload_url . basename($_FILES['image']['name']);
} catch (Exception $e) {
// Exception occurred. Make error flag true
$response['error'] = true;
$response['message'] = $e->getMessage();
}
} else {
// File parameter is missing
$response['error'] = true;
$response['message'] = 'Not received any file!F';
}
// Echo final json response to client
echo json_encode($response);
?>
If you follow the tutorial to the end and your Android App is working as expected on your device, the problem is more on the server side due to permission, your server doesn't allow you to save the file.
Try to set the location to a folder where your application will have permission to write to or change htaccess you can get more info on http://httpd.apache.org/docs/2.2/howto/htaccess.html

Android - Display all images from server folder using PHP in GridView

I am trying to capture image or record a video using camera and then upload to my server. On the server side, i used PHP language to read the file and moved it to a particular location. Now i want to display all these images that are stored my server. Please help me.
This is the upload image PHP script
<?php
// Path to move uploaded files
$target_path = "uploads/";
// array for final json respone
$response = array();
// getting server ip address
$server_ip = gethostbyname(gethostname());
// final file url that is being uploaded
$file_upload_url = 'http://' . $server_ip . '/' . 'AndroidFileUpload' . '/' . $target_path;
if (isset($_FILES['image']['name'])) {
$target_path = $target_path . basename($_FILES['image']['name']);
// reading other post parameters
$email = isset($_POST['email']) ? $_POST['email'] : '';
$website = isset($_POST['website']) ? $_POST['website'] : '';
$response['file_name'] = basename($_FILES['image']['name']);
$response['email'] = $email;
$response['website'] = $website;
try {
// Throws exception incase file is not being moved
if (!move_uploaded_file($_FILES['image']['tmp_name'], $target_path)) {
// make error flag true
$response['error'] = true;
$response['message'] = 'Could not move the file!';
}
// File successfully uploaded
$response['message'] = 'File uploaded successfully!';
$response['error'] = false;
$response['file_path'] = $file_upload_url . basename($_FILES['image']['name']);
} catch (Exception $e) {
// Exception occurred. Make error flag true
$response['error'] = true;
$response['message'] = $e->getMessage();
}
} else {
// File parameter is missing
$response['error'] = true;
$response['message'] = 'Not received any file!F';
}
// Echo final json response to client
echo json_encode($response);
?>
upload Camera image:
i want to display theses images synchronised when i upload images again.
Config.java
public class Config {
// File upload url (replace the ip with your server address)
public static final String FILE_UPLOAD_URL = "http://wangjian.site90.net/AndroidFileUpload/fileUpload.php";
// Directory name to store captured images and videos
public static final String IMAGE_DIRECTORY_NAME = "Android File Upload";
I'm a newbie at this stuff so any help will be appreciated. thanks so much! And i will upload more details if needed.
Have an API endpoint return the URLs of the images that you have uploaded and then call them from the app.
Like,
public static final String FILE_DOWNLOAD_URL = "http://wangjian.site90.net/AndroidFileUpload/getUserPhotos.php";
Let this return some JSON Array like,
{
"urls" : [
{
"url" : "url of pic 1"
},
{
"url" : "url of pic 2"
},
..
]
}
Have a custom GridAdpater with an ImageView in it. Use libraries like Picasso to load the images from the url into your GridView using the custom adapter with a custom view (Here, ImageView).
Call this API endpoint every time when the user is on the screen so that you'll be able to fetch the list of uploaded photos and show them everytime.

Categories