I have a problem when attempting to use Fuel to send image to my server.
I am trying to use the Fuel.upload method.
Fuel.upload(urlfile).source { request, url ->
File(photopath)
}.responseString { request, response, result ->
}
the image is like : /storage/emulated/0/Android/data/fr.tais.riodi/files/Pictures/MyPicture4945313277123614993.jpg
$target_dir = "images/";
$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 tried to find an example of this operation. Have you an examples or an idea?
Thanks all
Related
I Have Problem ,
when i want to do the update method using slim framework.
my data can not be updated .
below is my code PHP :
$app->put('/eta1/{id}', function($request, $response, $args) use($app, $db){
$matkul = $request->getParams();
$eta1 = filter_var($matkul['eta1'], FILTER_SANITIZE_STRING);
$eta2 = filter_var($matkul['eta2'], FILTER_SANITIZE_STRING);
$query = $db->prepare('UPDATE tbl_matkul SET eta1=$eta1, eta2=$eta2 WHERE id = :id');
$query->bindParam('id', $args['id']);
$result = $query->execute();
$responseJson["error"] = false;
$responseJson["message"] = "Berhasil menambahkan ke database";
echo json_encode($responseJson);
});
Iam using retrofit in android client
Try this:
$app->put('/eta1/{id}', function($request, $response, $args) use($app, $db){
$matkul = $request->getParams();
$row = [
'id' => (int)$args['id'],
'eta1' => $matkul['eta1'],
'eta2' => $matkul['eta2'],
];
$sql = "UPDATE tbl_matkul SET eta1=:eta1, eta2=:eta2 WHERE id=:id;";
$status = $db->prepare($sql)->execute($row);
$responseJson = [];
if ($status) {
$responseJson["error"] = false;
$responseJson["message"] = "Berhasil menambahkan ke database";
} else {
$responseJson["error"] = true;
$responseJson["message"] = "Database operation failed";
}
return $response->withJson($responseJson);
});
so I want to upload an image using retrofit to my Slim framework API. Right now I can upload the images successfully using a seperate .php file in my other project that receives the images through the $_FILES object here is it
<?php
ini_set('display_errors',1);
ini_set('upload_max_filesize', '20M');
ini_set('post_max_size', '20M');
ini_set('max_input_time', 30000);
ini_set('max_execution_time', 30000);
require_once '../include/Functions.php';
$db = new Functions();
$result['error'] = true;
$result['message'] = 'Error occurred, try again1';
$userfk = $_POST['userid'];
$fileNames = array();
for($i = 0; $i < count ( $_FILES ['file'] ['name'] ); $i ++) {
try {
$extension = pathinfo($_FILES ['file'] ["name"][$i], PATHINFO_EXTENSION);
array_push($fileNames,microtime_float().'_'.rand(1, 99999999).'.'.$extension);
if (move_uploaded_file( $_FILES ['file'] ["tmp_name"][$i], "../images/iduploads/".$fileNames[$i])) {
$result['error'] = false;
$result['message'] = 'Upload success';
} else {
$result['error'] = true;
$result['message'] = 'Something went wrong, try again';
throw new Exception('Could not move file');
}
} catch (Exception $e) {
$result['error'] = true;
$result['message'] = 'Error, photos did not upload, try again';
}
}
if(count ( $_FILES ['file'] ['name']) > 0 && !empty($fileNames))
$db->uploadIdentificationDocs($userfk, $fileNames[0], $fileNames[1], $fileNames[2]);
echo json_encode($result);
function microtime_float(){
list($usec, $sec) = explode(" ", microtime());
return ((float)$usec + (float)$sec);
}
?>
And from my Android side I use
#POST("idUpload.php")
Call<Result> uploadMultiFile(#Body RequestBody file);
And
APIService service = retrofit.create(APIService.class);
MultipartBody.Builder builder = new MultipartBody.Builder();
builder.setType(MultipartBody.FORM);
User user = SharedPreferencesUtils.getUserPreferences(this);
builder.addFormDataPart("userid", user.getUserId());
builder.addFormDataPart("file[]", profilePicture.getName(), RequestBody.create(MediaType.parse("multipart/form-data"), profilePicture));
MultipartBody requestBody = builder.build();
ProgressRequestBody progressRequestBody = new ProgressRequestBody(requestBody, this);
Call<Result> call = service.uploadMultiFilee(progressRequestBody);
This works but I don't like the idea of leaving Slimto upload the image, reason I choose it is because of it's simplicity and clean code. This feels wrong, so I tried uploading using slims' provided functions
$app->post('/uploadprofilepicture/{userid}', function (Request $request, Response $response) {
$db = new Functions();
$userFk = $request->getAttribute('userid');
$result['error'] = true;
$result['message'] = 'Received here';
try {
$uploadedFiles = $request->getUploadedFiles();
if ($uploadedFile->getError() === UPLOAD_ERR_OK) {
$filename = moveUploadedFile($directory, $uploadedFile);
$result['error'] = true;
$result['message'] = 'Upload successs image '.$filename;
}
}catch (Exception $e) {
$result['error'] = true;
$result['message'] = 'Error occured: '.$e;
}
$response->getBody()->write((json_encode($result)));
});
But it fails, it just returns error 500, after running postman Call to a member function getError() on null meaning $request->getUploadedFiles() is null
#Zamrony was right, well at least he helped me figure out my issue, in the end here is the working code
use Slim\Http\UploadedFile;
$profilePhotoContainer = $app->getContainer();
$profilePhotoContainer['upload_directory'] = '../images/iduploads/';
$app->post('/uploadprofilepicture', function (Request $request, Response $response) {
$db = new Functions();
$directory = $this->get('upload_directory');
$result['error'] = true;
$result['message'] = 'Received here';
try {
$uploadedFiles = $request->getUploadedFiles();
$uploadedFile = $uploadedFiles['profilephoto'];
if ($uploadedFile->getError() === UPLOAD_ERR_OK) {
$filename = moveUploadedFile($directory, $uploadedFile);
$result['error'] = true;
$result['message'] = 'Upload successs image '.$filename;
}
}catch (Exception $e) {
$result['error'] = true;
$result['message'] = 'Error occured: '.$e;
}
$response->getBody()->write((json_encode($result)));
});
function moveUploadedFile($directory, UploadedFile $uploadedFile){
$extension = pathinfo($uploadedFile->getClientFilename(), PATHINFO_EXTENSION);
$basename = bin2hex(random_bytes(8));
$filename = sprintf('%s.%0.8s', $basename, $extension);
$uploadedFile->moveTo($directory . DIRECTORY_SEPARATOR . $filename);
return $filename;
}
It should be $uploadedFiles not $uploadedFile . That is why you get null.
Edit: $uploadedFile variable is not initialized. That is why you get null. For example if html is defined as follow
<form method="post" enctype="multipart/form-data">
<input type="file" name="myUploadedFile">
</form>
Then in code that handle file upload, it should be
$uploadedFiles = $request->getUploadedFiles();
$uploadedFile = $uploadedFiles['myUploadedFile'];
if ($uploadedFile->getError() === UPLOAD_ERR_OK) {
//TODO: move file
}
Read Uploading files using POST forms for more information.
I created image uploading through a XAMPP server using PHP. But I need to
know how to delete the uploaded image file from Android. How can I do that?
php file(upload) :
<?PHP
if(isset($_POST['image'])){
$now = DateTime::createFromFormat('U.u', microtime(true));
$id = $now->format('YmdHisu');
$upload_folder = "upload/";
$path = "$upload_folder/$id.jpeg";
$image = $_POST['image'];
if(file_put_contents($path, base64_decode($image)) != false){
echo "uploaded_success";
exit;
}
else
{
echo "Sorry, your file is too large.";
echo "upload_failed";
exit;
}
}
else{
echo "image_not_in";
exit;
}
?>
You can get the photo path and delete it in the successful response from the server!
make sure you declare permission in the manifest!
<uses-permission> android:name="android.permission.WRITE_INTERNAL_STORAGE" />
in you code..
PostResponseAsyncTask task = new PostResponseAsyncTask(MainActivity.this, postData, new AsyncResponse() {
#Override
public void processFinish(String s) {
if (s.contains("uploaded_success")) {
File photoDelete = new File(selectedPhoto);
if (photoDelete.exists()) {
if (photoDelete.delete()) {
Log.d("DELETE", "deleted:" + selectedPhoto);
}
}
Toast.makeText(getApplicationContext(), "Image Uploaded Successfully", Toast.LENGTH_SHORT).show();
} else {
Toast.makeText(getApplicationContext(), "Error while uploading...", Toast.LENGTH_SHORT).show();
}
}
});
You can delete an image from your server by sending a command from your app (client) to the server asking the server to delete the file from its local storage.
Let's say you set the imageName of your image file to to hashmap to send to the server by:
HashMap<String, String> postData = new HashMap<String, String>();
postData.put("deleteImage", imageName);
and execute it:
task.execute("http://192.168.1.7/news/delete.php");
Now, you just need to see if the value of the deleteImage is set or not (on your server, in the delete.php file) by and delete the file by calling unlink method in PHP:
Delete.php
<?PHP
if(isset($_POST['deleteImage'])){
$imageName = $_POST['deleteImage'];
unlink($imageName) //this deletes the image file
}
?>
I am struggling with one situation. I am returning some json data from PHP server my code is as follows,
PHP API code:
if ($user != false) {
$result = mysql_query("SELECT stock_name,stock_location FROM btrack_stock WHERE user_id= '$user_id'") or die(mysql_error());
$rows = array();
$count = mysql_num_rows($result);
if($count > 0){
while ($r = mysql_fetch_assoc($result)) {
$rows[] = $r;
}
echo json_encode(array('usertransaction' => $rows));
}else{
$response["error"] = 1;
$response["error_msg"] = "You do not have any transaction so far. ";
echo json_encode($response);
}
}
On android side, I use a class that extends AsyncTask and on my onPostExecute I use:
protected void onPostExecute(JSONObject json) {
try {
if(json.getString("error_msg") != null){
String err = json.getString("error_msg");
stock_error.setText(err);
stock_error.setVisibility(View.VISIBLE);
pDialog.dismiss();
}else{
pDialog.dismiss();
Toast.makeText(getApplicationContext(), "Success", Toast.LENGTH_LONG).show();
}
}catch (JSONException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
Well actually, I wanted to display error message that is returned from PHP server and display all the data if I got success message (here I am showing a Toast).
My question is how can we display error message if json returns error message and display success if json does not return error message.
* My code works fine if I get error_msg as json response but if I return other data the app stuck in process dialog with a warning in LogCat as " There is no value for error_msg".
Thanks in Advance.
Try this:
if json.isNull("error_msg") {
do_something()
}
else {
json.getString("error_msg");
do_something_else()
}
I tried several ways to upload a file on the FTP server, but I failed in that.
Here I am pasting My server code (php)to accept the file from the device, please provide android code corresponding to that server code.
<?php
error_reporting(0);
include("dbconfig.php");
$msg = '';
$status = 1;
$overwrite = 1;
/*echo "<pre>";
print_r($_POST);
echo "</pre>";*/
/*echo "<pre>";
print_r($_FILES);
echo "</pre>";*/
if(trim($_POST['userid'])!='')
{
$userid = trim($_POST['userid']);
$overwrite = trim($_POST['overwrite']);
if($overwrite == 0)
{
$selfilesqry = mysql_query("SELECT filepath FROM userfiles WHERE userid = 1 AND status=1");
while($row = mysql_fetch_array($selfilesqry))
{
$selfiles[] = $row['filepath'];
}
}
/* echo "<pre>";
print_r($selfiles);
echo "</pre>";*/
$host = '97.***.****';
$usr = '*****************8';
$pwd = '**********************';
$paths = '/mobbisys/cloudbin/data';
//$paths = '/php_projects/mahesh/ftpupload/data';
// connect to FTP server (port 21)
$conn_id = ftp_connect($host, 21) or die ("Cannot connect to host");
// send access parameters
ftp_login($conn_id, $usr, $pwd) or die("Cannot login");
for($i=0; $i<count($_FILES['txtfile']['name']); $i++)
{
if($_FILES['txtfile']['name'][$i]!='')
{
$type = explode('/',$_FILES['txtfile']['type'][$i]);
$filetype = $type[0];
if($filetype == 'audio')
{
$path = $paths."/audio";
}
else if($filetype == 'video')
{
$path = $paths."/video";
}
else if($filetype == 'image')
{
$path = $paths."/image";
}
else
{
$path = $paths."/misc";
}
//echo "<br />".$path;
$name = $_FILES['txtfile']['name'][$i];
$filep = $_FILES['txtfile']['tmp_name'][$i];
// turn on passive mode transfers (some servers need this)
// ftp_pasv ($conn_id, true);
$filepath = strtolower($path.'/'.$name);
if($overwrite == 1)
{
// perform file upload
$upload = ftp_put($conn_id, $path.'/'.$name, $filep, FTP_BINARY);
// check upload status:
if(!$upload)
{
$msg .= '<br />Cannot upload - '.$_FILES['txtfile']['name'][$i];
}
else
{
$msg .= '<br />Upload complete - '.$_FILES['txtfile']['name'][$i];
$sqlAdd = "INSERT INTO userfiles(userid, filetype, filepath, createddate, modifieddate, status) VALUES(".$userid.",'".$filetype."','".$filepath."',NOW(),NOW(),'".$status."') ";
$resAdd = mysql_query($sqlAdd);
}
}
else
{
if(in_array($filepath, $selfiles))
{
$msg .= '<br />Cannot upload - '.$_FILES['txtfile']['name'][$i].' already exist.';
}
else
{
// perform file upload
$upload = ftp_put($conn_id, $path.'/'.$name, $filep, FTP_BINARY);
// check upload status:
if(!$upload)
{
$msg .= '<br />Cannot upload - '.$_FILES['txtfile']['name'][$i];
}
else
{
$msg .= '<br />Upload complete - '.$_FILES['txtfile']['name'][$i];
$sqlAdd = "INSERT INTO userfiles(userid, filetype, filepath, createddate, modifieddate, status) VALUES(".$userid.",'".$filetype."','".$filepath."',NOW(),NOW(),'".$status."') ";
$resAdd = mysql_query($sqlAdd);
}
}
}
}
}
// close the FTP stream
ftp_close($conn_id);
}
else
{
$msg = 'Please provide userid';
}
echo $msg;
?>
You have to include move_uploaded_file function when you want insert
Syntax : move_uploaded_file ( string $filename , string $destination )
Example : move_uploaded_file($_FILES['uploadedfile']['tmp_name'], "./upload/".$_FILES["uploadedfile"]["name"]);
http://php.net/manual/en/function.move-uploaded-file.php
this is bad code. why not upload the files from android device via ftp without a server side script?
see here