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.
Related
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 :)
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);
}
}
Can anyone help me to make my code work, i.e. upload a file from Android to the server via PHP? I tried it in many different ways but it won't work. I get HTTP Response 200 but the files aren't uploaded on server.
The PHP script I'm using for upload is:
<?php
$uploaddir = 'uploads/';
$uploadfile = $uploaddir . basename($_FILES['uploaded_file']['name']);
if (move_uploaded_file($_FILES['uploaded_file']['tmp_name'], $uploadfile)) {
echo "File is valid, and was successfully uploaded.\n";
} else {
echo "Possible file upload attack!\n";
}
echo 'Here is some more debugging info:';
print_r($_FILES);
?>
I also tried using multipart from Httpmime 4.0 but it wont work.
public void uploadFile(String path)
{
File file = new File(path);
try {
HttpClient client = new DefaultHttpClient();
String postURL = upLoadServerUri;
HttpPost post = new HttpPost(postURL);
FileBody bin = new FileBody(file);
MultipartEntity reqEntity = new MultipartEntity(HttpMultipartMode.BROWSER_COMPATIBLE);
reqEntity.addPart("uploaded_file", bin);
post.setEntity(reqEntity);
HttpResponse response = client.execute(post);
HttpEntity resEntity = response.getEntity();
if (resEntity != null) {
Log.i("RESPONSE Wahaj: ","Code : "+ EntityUtils.toString(resEntity));
}
} catch (Exception e) {
e.printStackTrace();
}
}
public class Helpher extends AsyncTask<String, Void, String> {
Context context;
JSONObject json;
ProgressDialog dialog;
int serverResponseCode = 0;
DataOutputStream dos = null;
FileInputStream fis = null;
BufferedReader br = null;
public Helpher(Context context) {
this.context = context;
}
protected void onPreExecute() {
dialog = ProgressDialog.show(Main2Activity.this, "ProgressDialog", "Wait!");
}
#Override
protected String doInBackground(String... arg0) {
try {
File f = new File(arg0[0]);
URL url = new URL("http://localhost:8888/imageupload.php");
int bytesRead;
HttpURLConnection conn = (HttpURLConnection) url.openConnection();
conn.setDoOutput(true);
conn.setDoInput(true);
conn.setUseCaches(false);
conn.setRequestProperty("Content-Type", "multipart/form-data; boundary=" + BOUNDARY);
String contentDisposition = "Content-Disposition: form-data; name=\"keyValueForFile\"; filename=\""
+ f.getName() + "\"";
String contentType = "Content-Type: application/octet-stream";
dos = new DataOutputStream(conn.getOutputStream());
fis = new FileInputStream(f);
dos.writeBytes(SPACER + BOUNDARY + NEW_LINE);
dos.writeBytes(contentDisposition + NEW_LINE);
dos.writeBytes(contentType + NEW_LINE);
dos.writeBytes(NEW_LINE);
byte[] buffer = new byte[MAX_BUFFER_SIZE];
while ((bytesRead = fis.read(buffer)) != -1) {
dos.write(buffer, 0, bytesRead);
}
dos.writeBytes(NEW_LINE);
dos.writeBytes(SPACER + BOUNDARY + SPACER);
dos.flush();
int responseCode = conn.getResponseCode();
if (responseCode != 200) {
Log.w(TAG,
responseCode + " Error: " + conn.getResponseMessage());
return null;
}
br = new BufferedReader(
new InputStreamReader(conn.getInputStream()));
StringBuilder sb = new StringBuilder();
String line = null;
while ((line = br.readLine()) != null) {
sb.append(line + "\n");
}
Log.d(TAG, "Sucessfully uploaded " + f.getName());
} catch (MalformedURLException e) {
} catch (IOException e) {
} finally {
try {
dos.close();
if (fis != null)
fis.close();
if (br != null)
br.close();
} catch (IOException e) {
e.printStackTrace();
}
}
return String.valueOf(serverResponseCode);
}
#Override
protected void onPostExecute(String result) {
dialog.dismiss();
}
}
This is the AsyncTask "Helpher" class used for upload image from Android. To call this class use like syntax below.
new Main2Activity.Helpher(this).execute(fileUri.getPath());
Here fileUri.getPath() local image location.
I'm trying to send post request from android application to server. In this request I want to send some text data (json) and picture.
But I can't get this data in server. Variables $_FILES, $_POST and even php://input is empty. But data is really transferred to server, because in $_SERVER I can find this:
[REQUEST_METHOD] => POST
[CONTENT_TYPE] => multipart/form-data; boundary=Jq7oHbmwRy8793I27R3bjnmZv9OQ_Ykn8po6aNBj; charset=UTF-8
[CONTENT_LENGTH] => 53228
What is the problem can be with this?
server is nginx 1.1
PHP Version 5.3.6-13ubuntu3.10
file_uploads = On
Here is my android code
RequestConfig config = RequestConfig.custom()
.setConnectTimeout(30000)
.setConnectionRequestTimeout(30000)
.setSocketTimeout(30000)
.setProxy(getProxy())
.build();
CloseableHttpClient client = HttpClientBuilder.create()
.setDefaultRequestConfig(config)
.build();
HttpPost post = new HttpPost("http://example.com");
try {
JSONObject root = new JSONObject();
root.put("id", id);
if (mSettings != null) {
root.put("settings", SettingsJsonRequestHelper.getSettingsJson(mSettings));
}
MultipartEntityBuilder builder = MultipartEntityBuilder.create().setMode(HttpMultipartMode.BROWSER_COMPATIBLE);
File screenshot = getScreenshotFile();
if (screenshot.exists()) {
builder.addPart("screenshot", new FileBody(screenshot, ContentType.create("image/jpeg")));
}
builder.addTextBody("data", root.toString(), ContentType.create("text/json", Charset.forName("UTF-8")));
builder.setCharset(MIME.UTF8_CHARSET);
post.setEntity(builder.build());
} catch (JSONException e) {
Logger.getInstance().log(e);
}
try {
HttpResponse response = client.execute(post);
if (response.getStatusLine().getStatusCode() == HttpStatus.SC_OK) {
mResponse.setResponse(response.getEntity().getContent());
} else {
Logger.getInstance().log("response error. Code " + response.getStatusLine().getStatusCode());
}
} catch (ClientProtocolException e) {
Logger.getInstance().log(e);
} catch (IOException e) {
Logger.getInstance().log(e);
}
Maybe you have te change php.ini parameters like enable_post_data_reading=on increase post_max_size and upload_max_filesize
Not sure of the method you are using and you did not include your server side processing file. Error may be from either one. But try this. I first send it a file path through the params and named it 'textFileName'.
#Override
protected String doInBackground(String... params) {
// File path
String textFileName = params[0];
String message = "This is a multipart post";
String result =" ";
//Set up server side script file to process it
HttpPost post = new HttpPost("http://10.0.2.2/test/upload_file_test.php");
File file = new File(textFileName);
//add image file and text to builder
MultipartEntityBuilder builder = MultipartEntityBuilder.create();
builder.setMode(HttpMultipartMode.BROWSER_COMPATIBLE);
builder.addBinaryBody("uploaded_file", file, ContentType.DEFAULT_BINARY, textFileName);
builder.addTextBody("text", message, ContentType.DEFAULT_BINARY);
//enclose in an entity and execute, get result
HttpEntity entity = builder.build();
post.setEntity(entity);
HttpClient client = new DefaultHttpClient();
try {
HttpResponse response = client.execute(post);
BufferedReader reader = new BufferedReader(new InputStreamReader(
response.getEntity().getContent(), "UTF-8"));
String sResponse;
StringBuilder s = new StringBuilder();
while ((sResponse = reader.readLine()) != null) {
s = s.append(sResponse);
}
System.out.println("Response: " + s);
} catch (ClientProtocolException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
return message;
}
Server side php looks like:
<?php
$target_path1 = "uploads/";
/* Add the original filename to our target path.
Result is "uploads/filename.extension" */
$status = "";
if(isset($_FILES["uploaded_file"])){
echo "Files exists!!";
// if(isset($_POST["text"])){
// echo "The message files exists! ".$_POST["text"];
// }
$target_path1 = $target_path1 . basename( $_FILES['uploaded_file']['name']);
if(move_uploaded_file($_FILES['uploaded_file']['tmp_name'], $target_path1)) {
$status= "The first file ". basename( $_FILES['uploaded_file']['name']).
" has been uploaded.";
}
else{
$status= "There was an error uploading the file, please try again!";
$status.= "filename: " . basename( $_FILES['uploaded_file']['name']);
$status.= "target_path: " .$target_path1;
}
}else{
echo "Nothing in files directory";
}
$array["status"] = "status: ".$status;
$json_object = json_encode($array);
echo $json_object;
?>
In my android app, I've to upload file to server and read the file at server side. File is being uploaded but some times what happen, in folder (at server in which file resides) if previously uploaded file exists, then the current uploaded file is generated with previous file data. e.g. say if I upload file named A to server with data say '1, 2 and 3' then there will be file A.txt under folder at server side with same data, and if now I upload file named B to server with data say 'A, B and C' then file B.txt under folder will be there but with previous file data of A.txt. So in B.txt, data is '1, 2 and 3'. Below is my code. What can be the issue?
Android Side
public void uploadUserFriendId(String user_id, String filePath, String fileName)
{
String server_url = "http://addressofserver/folder/myfile.php";
InputStream inputStream;
try
{
inputStream = new FileInputStream(new File(filePath));
byte[] data;
try
{
data = IOUtils.toByteArray(inputStream);
HttpClient httpClient = new DefaultHttpClient();
httpClient.getParams().setParameter(CoreProtocolPNames.USER_AGENT,
System.getProperty("http.agent"));
HttpPost httpPost = new HttpPost(server_url);
InputStreamBody inputStreamBody = new InputStreamBody(new ByteArrayInputStream(data), fileName);
MultipartEntity multipartEntity = new MultipartEntity();
multipartEntity.addPart("file", inputStreamBody);
multipartEntity.addPart("user_id", new StringBody(user_id));
httpPost.setEntity(multipartEntity);
HttpResponse httpResponse = httpClient.execute(httpPost);
// Handle response back from script.
if(httpResponse != null) {
//Toast.makeText(getBaseContext(), "Upload Completed. ", 2000).show();
} else { // Error, no response.
//Toast.makeText(getBaseContext(), "Server Error. ", 2000).show();
}
} catch (IOException e) {
e.printStackTrace();
}
} catch (FileNotFoundException e1) {
e1.printStackTrace();
}
}
PHP Side
<?php
error_reporting(~0);
ini_set('display_errors', 1);
mysql_connect("localhost", "root", "Admin#123") or die(mysql_error()) ;
mysql_select_db("retail_menu") or die(mysql_error()) ;
$today =date("YmdHis");
$pic=$today.".txt";
if (isset($_POST["user_id"]) && !empty($_POST["user_id"]))
{
$user_id=$_POST['user_id'];
}
else
{
$user_id="null";
}
$objFile = & $_FILES["file"];
// here file is created under folder named upload at server side
if( move_uploaded_file( $objFile["tmp_name"], "upload/".$user_id.".txt" ) )
{
$file = fopen("upload/".$user_id.".txt" ,"r");
while(! feof($file))
{
$friend_id = fgets($file, 8192);
if($friend_id!= null)
{
$query = "INSERT IGNORE INTO table_name (user_id, friend_id) values('$user_id', '$friend_id')";
var_dump($query);
mysql_query($query);
}
}
fclose($file);
}
else
{
print "There was an error uploading the file, please try again!";
}
?>