could not be able to upload file to server using retrofit2 - php

I want to upload .pdf file to server where php code is
<?php
$con = mysqli_connect("localhost","db_user","pwd","api_db");
$user_id = $_POST['id'];
$title = $_POST['cvTitle'];
$allowedExts = array("docx","doc", "pdf", "txt");
$temp = explode(".", $_FILES['cvfile']["name"]);
$extension = end($temp);
if ((($_FILES["cvfile"]["type"] == "application/pdf")
|| ($_FILES["cvfile"]["type"] == "application/text/plain")
|| ($_FILES["cvfile"]["type"] == "application/msword")
|| ($_FILES["cvfile"]["type"] == "application/vnd.openxmlformats-officedocument.wordprocessingml.document"))
&& in_array($extension, $allowedExts)){
//inner if
if ($_FILES["cvfile"]["error"] > 0){
echo "Failed 1";
} else{
}// end inner else
$f_name = time().$_FILES['cvfile']["name"];
move_uploaded_file($_FILES['cvfile']["tmp_name"],
"upload/" . $f_name);
$file_name = $f_name;
} else {
$json = array("File Type Not Allowed");
header('content-type: application/json');
echo json_encode($json);
} // end else
$query = "UPDATE users set cv = '$file_name', cvTitle = '$title' where id = '$user_id'";
if (mysqli_query($db,$query)) {
$json = array("cv" => $file_name, "cvTitle" => $title);
header('content-type: application/json');
echo json_encode($json);
}
?>
my service is
#FormUrlEncoded
#Multipart
#POST("updatecv.php")
Call<User> uploadUserCV(#Field("id") String id,
#Field("cvTitle") String cvTitle,
#Part MultipartBody.Part cv);
and finally I'm making call as
#Override
public boolean onOptionsItemSelected(MenuItem item) {
switch (item.getItemId()){
case R.id.action_cv : {
Intent intent = new Intent(Intent.ACTION_GET_CONTENT);
intent.addCategory(Intent.CATEGORY_OPENABLE);
intent.setType("*/*");
startActivityForResult(Intent.createChooser(intent, "Choose file using"), Constant.REQUEST_CODE_OPEN);
return true;
}
}
return super.onOptionsItemSelected(item);
}
#Override
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
super.onActivityResult(requestCode, resultCode, data);
try {
if (requestCode == Constant.REQUEST_CODE_OPEN){
if (resultCode == RESULT_OK && null != data){
String type = Utils.getMimeType(UpdateProfileActivity.this, data.getData());
if (validateFileType(type)){
// Get the Image from data
Uri selectedFile = data.getData();
String[] filePathColumn = {MediaStore.Files.FileColumns.DATA};
Cursor cursor = getContentResolver().query(selectedFile, filePathColumn, null, null, null);
assert cursor != null;
cursor.moveToFirst();
int columnIndex = cursor.getColumnIndex(filePathColumn[0]);
mediaPath = cursor.getString(columnIndex);
cursor.close();
uploadFile();
} else {
Toast.makeText(UpdateProfileActivity.this, "File type is not allowed", Toast.LENGTH_SHORT).show();
}
Log.e("FILE_TYPE", Utils.getMimeType(UpdateProfileActivity.this, data.getData()));
}
}
} catch (Exception e){
e.printStackTrace();
}
}
// Uploading CV
private void uploadFile() {
final Dialog dialog = Utils.showPreloaderDialog(UpdateProfileActivity.this);
dialog.show();
// Map is used to multipart the file using okhttp3.RequestBody
File file = new File(mediaPath);
// Parsing any Media type file
final RequestBody requestBody = RequestBody.create(MediaType.parse("*/*"), file);
MultipartBody.Part fileToUpload = MultipartBody.Part.createFormData("file", file.getName(), requestBody);
mUserCall = mRestManager.getApiService().uploadUserCV(uid, file.getName(), fileToUpload);
mUserCall.enqueue(new Callback<User>() {
#Override
public void onResponse(Call<User> call, Response<User> response) {
User user = response.body();
Log.e("UPLOADED_FILE", "name is " + user.getCvTitle());
dialog.dismiss();
}
#Override
public void onFailure(Call<User> call, Throwable t) {
dialog.dismiss();
Log.e("UPLOADED_FILE_ERROR", "Message is " + t.getMessage());
Toast.makeText(UpdateProfileActivity.this, "Something went wrong", Toast.LENGTH_SHORT).show();
}
});
}
private boolean validateFileType(String type){
String [] allowedFileTypes = {"application/vnd.openxmlformats-officedocument.wordprocessingml.document",
"application/msword", "text/plain", "application/pdf"};
for (int i = 0; i<=allowedFileTypes.length; i++){
if (allowedFileTypes[i].equals(type)){
return true;
}
}
return false;
}
but this code is not uploading the file to server no any errors. I wan to know where are the things wrong in php code or in android side.
Any help is highly appreciated.

According to your PHP, you're looking for form-data part with name cvfile, but in Android code you're passing file as a name of the form-data part. So all you need is to change file to cvfile, like this:
MultipartBody.Part fileToUpload = MultipartBody.Part.createFormData("cvfile", file.getName(), requestBody);
Hopefully it should work.

It seems you are testing on localhost then inside app localhost url is needed ....to grab that
type ipconfig (in cmd on windows)
copy that ip which is connected to lan or wifi.
then check is upload.php file present or not on that ip address.
for eg : 192.168.1.102/upload.php
after that copy the ip and
add in base url of retrofit builder in retrofit client class.
Hope it will solve your issue :)

Related

Retrofit 2 Working In Postman and Localhost but Not On Amazon AWS Live Server

My retrofit instance is working fine with localhost (both android code and postman), and working fine online with postman. But when I go to Amazon AWS instance (a.k.a online) the android part is not working. Please see my code below. The error log from android is D/response: {"error":true,"message":"Required parameters are not available"}
Interestingly the problem is with large file sizes 2M, small file sizes 24KB are getting uploaded fine. I have already checked the php.ini file the max sizes there are 25MB
I am following this tutorial : https://www.simplifiedcoding.net/retrofit-upload-file-tutorial/
public interface Api {
//the base URL for our API
//make sure you are not using localhost
//find the ip usinc ipconfig command
String BASE_URL = "http://creative-thinker.com/files/images/secret_crushes/";
//this is our multipart request
//we have two parameters on is name and other one is description
#Multipart
#POST("Api.php?apicall=upload")
Call<MyResponse> uploadImage(#Part("image\"; filename=\"myfile.jpg\" ")
RequestBody file, #Part("desc") RequestBody desc);
}
My Object Class
public class MyResponse {
public boolean error;
String message;
}
My Fragment
ivImageView.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
// Open The File Choose And Send To Activity For Result
Intent i = new Intent(Intent.ACTION_PICK, MediaStore.Images.Media.EXTERNAL_CONTENT_URI);
startActivityForResult(i, 100);
}
});
#Override
public void onActivityResult(int requestCode, int resultCode, Intent data) {
super.onActivityResult(requestCode, resultCode, data);
if (requestCode == 100 && data != null) {
//the image URI
Uri selectedImage = data.getData();
//calling the upload file method after choosing the file
uploadFile(selectedImage, "My Image");
}
}
private void uploadFile(Uri fileUri, String desc) {
//creating a file
File file = new File(getRealPathFromURI(fileUri));
//creating request body for file
RequestBody requestFile = RequestBody.create(MediaType.parse(getContext().getContentResolver().getType(fileUri)), file);
RequestBody descBody = RequestBody.create(MediaType.parse("text/plain"), desc);
//The gson builder
Gson gson = new GsonBuilder()
.setLenient()
.create();
//creating retrofit object
Retrofit retrofit = new Retrofit.Builder()
.baseUrl(Api.BASE_URL)
.addConverterFactory(GsonConverterFactory.create(gson))
.build();
//creating our api
Api api = retrofit.create(Api.class);
//creating a call and calling the upload image method
Call<MyResponse> call = api.uploadImage(requestFile, descBody);
//finally performing the call
call.enqueue(new Callback<MyResponse>() {
#Override
public void onResponse(Call<MyResponse> call, Response<MyResponse> response) {
if (!response.body().error) {
Toast.makeText(getContext().getApplicationContext(), "File Uploaded Successfully...", Toast.LENGTH_LONG).show();
} else {
MyResponse res= response.body();
Log.d("response", new Gson().toJson(res));
Toast.makeText(getContext().getApplicationContext(), "Some error occurred...", Toast.LENGTH_LONG).show();
}
}
#Override
public void onFailure(Call<MyResponse> call, Throwable t) {
Toast.makeText(getContext().getApplicationContext(), t.getMessage(), Toast.LENGTH_LONG).show();
}
});
}
/*
* This method is fetching the absolute path of the image file
* if you want to upload other kind of files like .pdf, .docx
* you need to make changes on this method only
* Rest part will be the same
* */
private String getRealPathFromURI(Uri contentUri) {
String[] proj = {MediaStore.Images.Media.DATA};
CursorLoader loader = new CursorLoader(getContext(), contentUri, proj, null, null, null);
Cursor cursor = loader.loadInBackground();
int column_index = cursor.getColumnIndexOrThrow(MediaStore.Images.Media.DATA);
cursor.moveToFirst();
String result = cursor.getString(column_index);
cursor.close();
return result;
}
FileHandler.php
<?php
class FileHandler
{
private $con;
public function __construct()
{
require_once dirname(__FILE__) . '/DbConnect.php';
$db = new DbConnect();
$this->con = $db->connect();
}
public function saveFile($file, $extension, $desc)
{
$name = round(microtime(true) * 1000) . '.' . $extension;
$filedest = dirname(__FILE__) . UPLOAD_PATH . $name;
move_uploaded_file($file, $filedest);
$url = $server_ip = gethostbyname(gethostname());
$stmt = $this->con->prepare("INSERT INTO images (description, image) VALUES (?, ?)");
$stmt->bind_param("ss", $desc, $name);
if ($stmt->execute()) {
return true;
}
return false;
}
public function getAllFiles()
{
$stmt = $this->con->prepare("SELECT id, description, image FROM images ORDER BY id DESC");
$stmt->execute();
$stmt->bind_result($id, $desc, $url);
$images = array();
while ($stmt->fetch()) {
$temp = array();
$absurl = 'http://' . gethostbyname(gethostname()) . '/files/images/secret_crushes' . UPLOAD_PATH . $url;
$temp['id'] = $id;
$temp['desc'] = $desc;
$temp['url'] = $absurl;
array_push($images, $temp);
}
return $images;
}
}
Api.php
<?php
require_once dirname(__FILE__) . '/FileHandler.php';
$response = array();
if (isset($_GET['apicall'])) {
switch ($_GET['apicall']) {
case 'upload':
if (isset($_POST['desc']) && strlen($_POST['desc']) > 0 && $_FILES['image']['error'] === UPLOAD_ERR_OK) {
$upload = new FileHandler();
$file = $_FILES['image']['tmp_name'];
$desc = $_POST['desc'];
if ($upload->saveFile($file, getFileExtension($_FILES['image']['name']), $desc)) {
$response['error'] = false;
$response['message'] = 'File Uploaded Successfullly';
}
} else {
$response['error'] = true;
$response['message'] = 'Required parameters are not available';
}
break;
case 'getallimages':
$upload = new FileHandler();
$response['error'] = false;
$response['images'] = $upload->getAllFiles();
break;
}
}
echo json_encode($response);
function getFileExtension($file)
{
$path_parts = pathinfo($file);
return $path_parts['extension'];
}
I am trying to catch the values of items in Api.php using
$response['message'] = $string; just where $response['message'] = 'Required parameters are not available';
and getting the following results
$string = $_POST['desc'];
D/response: {"error":true,"message":"My Image"}
$string = $_POST['desc'];
$string = strlen($string);
D/response: {"error":true,"message":"8"}
$string = $_FILES['image']['error'];
D/response: {"error":true}
$string = UPLOAD_ERR_OK;
D/response: {"error":true,"message":"0"}
And removing && $_FILES['image']['error'] === UPLOAD_ERR_OK enters the data into database but no image still uploaded
Finally found the solution after searching the net... The issue was file size
I am on php 7 and Apache. So the configuration needs to changed at two places
The configuration
upload_max_filesize = 25M
post_max_size = 25M
max_execution_time = 300
max_input_time = 300
memory_limit = 128M
The locations
sudo nano /etc/php/7.0/fpm/php.ini
sudo nano /etc/php/7.0/apache2/php.ini
Apparently the settings needs to be changed for PHP AND Apache on Amazon AWS. Hope it helps others.

Uploading SVG Laravel 5.5

How do I properly upload a svg file with Laravel 5.5?
The standard image validation rule does not see it as a proper image (image|mimes:jpeg,png,jpg,gif,svg)
When I remove all validation, the file get's stored as a txt file.
My upload code:
$request->file('image')->store('images', 'public');
This Will Work
Use Like This Will Work
if ($request->hasFile('file')) {
$file = $request->file('file');
$file->move($file, 'uploads/audio');
}
from a svg string creating a file, I didn't succeed with string sending as it abuses about some wrong chars after it been transmited to Laravel. So far from Android by okhttp:
private static final MediaType MEDIA_TYPE_TXT =MediaType.parse("text/plain");
....
MultipartBody.Builder obj_ = new MultipartBody.Builder().setType(MultipartBody.FORM);
fileImzo_ = new File(fileSafar_.getAbsoluteFile().getParentFile().getAbsolutePath(),"imzo.txt");
String nomiImzo_ = fileImzo_.getName();
//svgImzo is a raw SVG xml string
InputStream stream_ = new ByteArrayInputStream(svgImzo.getBytes(StandardCharsets.UTF_8));
try {
try (OutputStream output_ = new FileOutputStream(fileImzo_)) {
byte[] buffer = new byte[4 * 1024]; // or other buffer size
int read;
while ((read = stream_.read(buffer)) != -1) {
output_.write(buffer, 0, read);
}
output_.flush();
}
}catch(Exception e){
e.printStackTrace();
} finally {
try {
stream_.close();
} catch (IOException e) {
e.printStackTrace();
}
}
obj_.addFormDataPart("fileImzo", nomiImzo_, RequestBody.create(fileImzo_, MEDIA_TYPE_TXT));
}
RequestBody req = obj_
.addFormDataPart("copayDodmi", "" + copayDodmi)
.addFormDataPart("izoh", xavar.getText().toString())
.addFormDataPart("driver_id", "" + driverId_)
.build();
Request request = new Request.Builder()
.header("Authorization", "Bearer " + token)//Authorization
.url(MehmonxonaActivity.URLI_ASSOSI + "/supurdani_paket_dodashud")
.post(req)
.build();
....
in Laravel controller , say we add the file path to array to update a row in the table:
....
if ($request->hasFile('fileImzo')) {
$imzo_filename = $this->sozuNomiFaylate('fileImzo', $request);
if (!is_null($imzo_filename)) {
$arr['signature_svg'] = $imzo_filename;
}
}
....
and the function sozuNomiFaylate():
....
private function sozuNomiFaylate(string $alias, \Illuminate\Http\Request $request)
{
$separatorLcl = DIRECTORY_SEPARATOR;
$image = $request->file($alias);
$ext=$image->getClientOriginalExtension();
if($ext==='svg' || $ext==='SVG' || $ext==='txt'|| $ext==='')
$ext='svg';
$filename = time() . '.' .$ext ;
$path = public_path('images' . $separatorLcl . 'uploads' . $separatorLcl . $filename);
if($ext==='svg' || $ext==='SVG' || $ext==='txt'|| $ext===''){
File::put($path,$image->get());//Illuminate\Support\Facades\File
}else
try {
l::k($path);
Image::make($image)->save($path);
} catch (\Exception $e) {
l::k($e->getMessage());
l::k($e->getTraceAsString());
l::k('fayl soxta na shud');
return null;
}
return $filename;
}
....
And you are done

Get location from image in android to php and sometimes error couldn't get location

I'm using AS
first case : I'm running android app from PC A to device kitkat and marshmallow, then I'm trying to upload image to server and get the location using PHP. the result is when using device kitkat the GPS I can get it, but no in marshmallow
second case : I'm running android app from PC B, to device kitkat and marshmallow, then I'm trying to upload image to server and get the location using PHP. the result is I'm using kitkat and marshmallow the both cannot get GPS from image
third case : I'm running android app from PC B to device kitkat and marshmallow, then I'm trying to upload image to server and get the location using PHP. BUT for now I change the IP to connect server using IP on PC A. the result is when I using device kitkat the GPS I can get it, but using Marshmallow still cannot get the location
in code I have already using android runtime permission. there's no logcat error
how I can fix that?
and this code PHP
<?php
error_reporting(0);
$latitude = 0;
$longitude = 0;
$lokasi = "uploads/";
$file_name = $_FILES['image']['name'];
$file_ext = explode('.',$file_name);
$file_ext = strtolower(end($file_ext));
$file_size = $_FILES['image']['size'];
$file_tmp = $_FILES['image']['tmp_name'];
$filename = basename($_FILES['image']['name']);
$target_path = $lokasi . basename($_FILES['image']['name']);
echo basename($_FILES['image']['name'])."<BR>";
//get latitude and longitude
$image_file = $file_tmp;
echo "string : ".$image_file;
if(file_exists($image_file)){
$details = exif_read_data($image_file);
$sections = explode(',',$details['SectionsFound']);
if(in_array('GPS',array_flip($sections))){
echo $latitude = number_format(format_gps_data($details['GPSLatitude'],$details['GPSLatitudeRef']),10, ',', ' ');
$longitude = number_format(format_gps_data($details['GPSLongitude'],$details['GPSLongitudeRef']),10, ',', ' ');
}
else{
die('GPS data not found');
}
}
else{
die('File does not exists');
}
function format_gps_data($gpsdata,$lat_lon_ref){
$gps_info = array();
foreach($gpsdata as $gps){
list($j , $k) = explode('/', $gps);
array_push($gps_info,$j/$k);
}
$coordination = $gps_info[0] + ($gps_info[1]/60.00) + ($gps_info[2]/3600.00);
return (($lat_lon_ref == "S" || $lat_lon_ref == "W" ) ? '-'.$coordination : $coordination).' '.$lat_lon_ref;
}
///////////////////////////////
$nama_file = $latitude . "_" . $longitude . "." . $file_ext;
$target_path=$lokasi . $nama_file;
try {
//throw exception if can't move the file
if (!move_uploaded_file($file_tmp, $target_path)) {
throw new Exception('Could not move file');
}
echo "Success";
} catch (Exception $e) {
die('File did not upload: ' . $e->getMessage());
}
?>
and this code for upload image
private class UploadFileToServer extends AsyncTask<Void, Integer, String> {
#Override
protected void onPreExecute() {
// setting progress bar to zero
progressBar.setProgress(0);
super.onPreExecute();
}
#Override
protected void onProgressUpdate(Integer... progress) {
// Making progress bar visible
progressBar.setVisibility(View.VISIBLE);
// updating progress bar value
progressBar.setProgress(progress[0]);
// updating percentage value
txtPercentage.setText(String.valueOf(progress[0]) + "%");
}
#Override
protected String doInBackground(Void... params) {
return uploadFile();
}
#SuppressWarnings("deprecation")
private String uploadFile() {
String responseString = null;
HttpClient httpclient = new DefaultHttpClient();
HttpPost httppost = new HttpPost(Config.FILE_UPLOAD_URL);
try {
AndroidMultiPartEntity entity = new AndroidMultiPartEntity(
new ProgressListener() {
#Override
public void transferred(long num) {
publishProgress((int) ((num / (float) totalSize) * 100));
}
});
File sourceFile = new File(filePath);
// Adding file data to http body
entity.addPart("image", new FileBody(sourceFile));
image = new FileBody(sourceFile);
// Extra parameters if you want to pass to server
entity.addPart("website",
new StringBody("www.androidhive.info"));
entity.addPart("email", new StringBody("abc#gmail.com"));
totalSize = entity.getContentLength();
httppost.setEntity(entity);
// Making server call
HttpResponse response = httpclient.execute(httppost);
HttpEntity r_entity = response.getEntity();
int statusCode = response.getStatusLine().getStatusCode();
if (statusCode == 200) {
// Server response
responseString = EntityUtils.toString(r_entity);
} else {
responseString = "Error occurred! Http Status Code: "
+ statusCode;
}
} catch (ClientProtocolException e) {
responseString = e.toString();
} catch (IOException e) {
responseString = e.toString();
}
return responseString;
}
#Override
protected void onPostExecute(String result) {
Log.e(TAG, "Response from server: " + result);
// showing the server response in an alert dialog
showAlert(result);
super.onPostExecute(result);
}
}

Upload doc, pdf,xls etc, from android application to php server

I get stuck at that place and unable to send doc file to php server.
I am using this code.
Here is PHP code.
if($_SERVER['REQUEST_METHOD']=='POST'){
$image = $_POST['image'];
$name = $_POST['name'];
require_once('dbConnect.php');
$sql ="SELECT id FROM volleyupload ORDER BY id ASC";
$res = mysqli_query($con,$sql);
$id = 0;
while($row = mysqli_fetch_array($res)){
$id = $row['id'];
}
$path = "uploads/$id.doc";
$actualpath = "http://10.0.2.2/VolleyUpload/$path";
$sql = "INSERT INTO volleyupload (photo,name) VALUES ('$actualpath','$name')";
if(mysqli_query($con,$sql)){
file_put_contents($path,base64_decode($image));
echo "Successfully Uploaded";
}
mysqli_close($con);
}else{
echo "Error";
}
Here is Java code
private void showFileChooser() {
Intent intent = new Intent();
intent.setType("file/*");
intent.setAction(Intent.ACTION_GET_CONTENT);
startActivityForResult(Intent.createChooser(intent, "Select Picture"),
PICK_IMAGE_REQUEST);
}
I called asynTask on upload button.
if (v == buttonUpload) {
// uploadImage();
new PostDataAsyncTask().execute();
}
A function calls in doInBackground is
private void postFile() {
try {
// the file to be posted
String textFile = Environment.getExternalStorageDirectory()
+ "/Woodenstreet Doc.doc";
Log.v(TAG, "textFile: " + textFile);
// the URL where the file will be posted
String postReceiverUrl = "http://10.0.2.2/VolleyUpload/upload.php";
Log.v(TAG, "postURL: " + postReceiverUrl);
// new HttpClient
HttpClient httpClient = new DefaultHttpClient();
// post header
HttpPost httpPost = new HttpPost(postReceiverUrl);
File file = new File(filePath.toString());
FileBody fileBody = new FileBody(file);
MultipartEntity reqEntity = new MultipartEntity(
HttpMultipartMode.BROWSER_COMPATIBLE);
reqEntity.addPart("file", fileBody);
httpPost.setEntity(reqEntity);
// execute HTTP post request
HttpResponse response = httpClient.execute(httpPost);
HttpEntity resEntity = response.getEntity();
if (resEntity != null) {
String responseStr = EntityUtils.toString(resEntity).trim();
Log.v(TAG, "Response: " + responseStr);
// you can add an if statement here and do other actions based
// on the response
}
} catch (NullPointerException e) {
e.printStackTrace();
} catch (Exception e) {
e.printStackTrace();
}
}
The exception I get is that
java.io.FileNotFoundException: content:/com.topnet999.android.filemanager/storage/0F02-250A/test.doc: open failed: ENOENT (No such file or directory)
There is file in emulator - test.doc.
Is there is any thing I miss in code, please help me.
Or suggest a tutorial to upload pdf to php server.
Thanks In Advance.
Here is the solution of my question: -
Here is code of php file - file.php
<?php
// DISPLAY FILE INFORMATION JUST TO CHECK IF FILE OR IMAGE EXIST
echo '<pre>';
print_r($_FILES);
echo '</pre>';
// DISPLAY POST DATA JUST TO CHECK IF THE STRING DATA EXIST
echo '<pre>';
print_r($_POST);
echo '</pre>';
$file_path = "images/";
$file_path = $file_path . basename( $_FILES['file']['name']);
if(move_uploaded_file($_FILES['file']['tmp_name'], $file_path)) {
echo "file saved success";
} else{
echo "failed to save file";
}?>
Put this file in htdoc folder of Xampp inside test named folder (if there is test folder already then ok, otherwise make a folder named "test"). And also create a folder named "images", in which uploaded file was saved.
Create function to select file from gallery
private void showFileChooser() {
Intent intent = new Intent(Intent.ACTION_GET_CONTENT);
intent.setType("application/*");
intent.addCategory(Intent.CATEGORY_OPENABLE);
try {
startActivityForResult(
Intent.createChooser(intent, "Select a File to Upload"),
1);
} catch (android.content.ActivityNotFoundException ex) {
Toast.makeText(getActivity(), "Please install a File Manager.",
Toast.LENGTH_SHORT).show();
}
}
Inside onActivityResult function
#Override
public void onActivityResult(int requestCode, int resultCode, Intent data) {
// TODO Auto-generated method stub
super.onActivityResult(requestCode, resultCode, data);
if (requestCode == 1) {
if (resultCode == Activity.RESULT_OK) {
Uri selectedFileURI = data.getData();
File file = new File(selectedFileURI.getPath().toString());
Log.d("", "File : " + file.getName());
uploadedFileName = file.getName().toString();
tokens = new StringTokenizer(uploadedFileName, ":");
first = tokens.nextToken();
file_1 = tokens.nextToken().trim();
txt_file_name_1.setText(file_1);
}
}
This is asyncTask to upload file to server,
public class PostDataAsyncTask extends AsyncTask<String, String, String> {
protected void onPreExecute() {
super.onPreExecute();
pDialog = new ProgressDialog(getActivity());
pDialog.setCancelable(false);
pDialog.setMessage("Please wait ...");
showDialog();
}
#Override
protected String doInBackground(String... strings) {
try {
HttpClient httpClient = new DefaultHttpClient();
HttpPost httpPost = new HttpPost("https://10.0.2.2/test/file.php");
file1 = new File(Environment.getExternalStorageDirectory(),
file_1);
fileBody1 = new FileBody(file1);
MultipartEntity reqEntity = new MultipartEntity(
HttpMultipartMode.BROWSER_COMPATIBLE);
reqEntity.addPart("file1", fileBody1);
httpPost.setEntity(reqEntity);
HttpResponse response = httpClient.execute(httpPost);
HttpEntity resEntity = response.getEntity();
if (resEntity != null) {
final String responseStr = EntityUtils.toString(resEntity)
.trim();
Log.v(TAG, "Response: " + responseStr);
}
} catch (NullPointerException e) {
e.printStackTrace();
} catch (Exception e) {
e.printStackTrace();
}
return null;
}
#Override
protected void onPostExecute(String result) {
hideDialog();
Log.e("", "RESULT : " + result);
}
}
Call the asyncTask on button click after selecting the file from gallery.
btn_upload.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View v) {
new PostDataAsyncTask().execute();
}
});
Hope this will help you.
Happy To Help and Happy Coding.
The code below is not tested ( as is ) but is generally how one might handle the file upload - there is, as you will see, a debug statement in there. Try to send the file and see what you get ~ if all lokks ok, comment out that line and keep your fingers crossed.
<?php
/* Basic file upload handler - untested */
if( $_SERVER['REQUEST_METHOD']=='POST' && isset( $_FILES['image'] ) && !empty( $_FILES['image']['tmp_name'] ) ){
/* Assuming the field being POSTed is called `image`*/
$name = $_FILES['image']['name'];
$size = $_FILES['image']['size'];
$type = $_FILES['image']['type'];
$tmp = $_FILES['image']['tmp_name'];
/* debug:comment out if this looks ok */
exit( print_r( $_FILES,true ) );
$result = $status = false;
$basename=pathinfo( $name, PATHINFO_FILENAME );
$filepath='http://10.0.2.2/VolleyUpload/'.$basename;
$result=#move_uploaded_file( $tmp, $filepath );
if( $result ){
$sql = "insert into `volleyupload` ( `photo`, `name` ) values ( '$filepath', '$basename' )";
$status=mysqli_query( $con, $sql );
}
echo $result && $status ? 'File uploaded and logged to db' : 'Something not quite right. Uploaded:'.$result.' Logged:'.$status;
}
?>
java.io.FileNotFoundException:
content:/com.topnet999.android.filemanager/storage/0F02-250A/test.doc:
open failed: ENOENT (No such file or directory)
What you have is a content provider path. Not a file system path.
So you cannot use the File... classes.
Instead use
InputStream is = getContentResolver().openInputStream(uri);
For the rest your php code does not make sense as there is no base64 encoding at upload. Further the $path and $actualpath parameters are not used and confusing. And you did not tell what your script should do.

PHP server: save (upload) image from Android with Retrofit

First of all, thank you for reading my question.
I have a PHP server where I wanted to upload an image from Android devices.
When I pick an image in my phone, it is uploaded as a TypedFile (retrofit.mime.TypedFile) to a PHP script.
When I want to see the image using a web browser or download the image with FTP client, the image is corrupted.
The Log shows me the image bytes and the downloaded file contains these bytes.
The first line of the image bytes is:
RIFF WEBPVP8 „ ¥ *,>Ñ`©P(%$##‘Œ9 i;\·û~œdàþ ÚKfëp‡ö~
(WebP mime type?)
My PHP script looks like this:
[...]
$pic = 'uploaded_images/' . $imagename . '.jpg';
if (!move_uploaded_file($_FILES['image']['tmp_name'], $pic)) {
echo "ko";die;
}
[...]
I have also tried fread, fwrite,... and this:
$file = file_get_contents($_FILES['image']['tmp_name']);
if (!$file) {echo 'file ko';die;}
//$file = unpack('h',$file);
if (!file_put_contents($pic, $file)) {echo 'ko';die;}
And some other combinations.
My Android request is (from Intent.ACTION_PICK or Intent.ACTION_IMAGE_CAPTURE):
#Override
public void onActivityResult(int requestCode, int resultCode, Intent imageReturnedIntent) {
super.onActivityResult(requestCode, resultCode, imageReturnedIntent);
switch (requestCode) {
case SELECT_PHOTO:
if (resultCode == Activity.RESULT_OK) {
final boolean isCamera;
if (imageReturnedIntent == null) {
isCamera = true;
} else {
final String action = imageReturnedIntent.getAction();
if (action == null) {
isCamera = false;
} else {
isCamera = action.equals(android.provider.MediaStore.ACTION_IMAGE_CAPTURE);
}
}
Uri selectedImageUri;
if (isCamera) {
selectedImageUri = outputFileUri;
} else {
selectedImageUri = imageReturnedIntent == null ? null : imageReturnedIntent.getData();
}
if (selectedImageUri != null) {
String selectedImagePath = null;
Cursor cursor = getActivity().getContentResolver().query(selectedImageUri, null, null, null, null);
if (cursor == null) {
selectedImagePath = selectedImageUri.getPath();
} else {
cursor.moveToFirst();
int idx = cursor.getColumnIndex(MediaStore.Images.ImageColumns.DATA);
selectedImagePath = cursor.getString(idx);
}
File photo = new File(selectedImagePath);
TypedFile typedImage = new TypedFile("image/*", photo);
// ProgressDialog lazy initialization
if (progress == null) {
progress = new ProgressDialog(getActivity());
progress.setTitle(getString(R.string.updating_data));
progress.setMessage(getString(R.string.please_wait));
progress.setCancelable(false);
progress.setIndeterminate(true);
}
progress.show();
Server.postUserImage(typedImage, imageCallback);
}
}
}
}
Server.postUserImage is a method where I configure the request.
The retrofit request interface is:
#Multipart
#POST("/user/image")
void postUserImage(#Part("image") TypedFile image, Callback<User> callback);
I appreciate so much your help. I have spent hours a couple of days looking for the reason and a solution for this.
Thank you very much.
I have solved it.
In case anyone has the same issue:
The bug was the mime type of the sended file: "image/*". For some reason, my PHP code is unable to save some images.
I have changed it to "application/octet-stream" and it works like a charm!
This is the old code:
File photo = new File(selectedImagePath);
TypedFile typedImage = new TypedFile("image/*", photo);
And this is the new code:
File photo = new File(selectedImagePath);
TypedFile typedImage = new TypedFile("application/octet-stream", photo);

Categories