I followed this tutorial and this answer on stackoverflow to upload a jpg image to server and save the image path in database using PHP.
The uploading function works but the image path cannot to added to database. Can someone help?
below is a copy of my android code and php code for uploading the image.
class UploadFile extends AsyncTask<String, Void, String> {
ProgressDialog loading;
@Override
protected void onPreExecute() {
super.onPreExecute();
loading = ProgressDialog.show(ViewTaskActivity.this, "Uploading photo", "Please wait...",true,true);
}
@Override
protected void onPostExecute(String message) {
super.onPostExecute(message);
loading.dismiss();
Toast.makeText(getApplicationContext(),message,Toast.LENGTH_LONG).show();
}
@Override
protected String doInBackground(String... arg0) {
String sourceFileUri = arg0[0];
String fileName = sourceFileUri;
HttpURLConnection conn = null;
DataOutputStream dos = null;
String lineEnd = "\r\n";
String twoHyphens = "--";
String boundary = "*****";
int bytesRead, bytesAvailable, bufferSize;
byte[] buffer;
int maxBufferSize = 1 * 1024 * 1024;
File sourceFile = new File(sourceFileUri);
if (!sourceFile.isFile()) {
loading.dismiss();
Log.e("uploadFile", "Source File not exist :" + uploadFilePath);
return "Source File not exist";
}
try {
// open a URL connection to the Servlet
FileInputStream fileInputStream = new FileInputStream(sourceFile);
URL url = new URL(upLoadServerUri);
// Open a HTTP connection to the URL
conn = (HttpURLConnection) url.openConnection();
conn.setDoInput(true); // Allow Inputs
conn.setDoOutput(true); // Allow Outputs
conn.setUseCaches(false); // Don't use a Cached Copy
conn.setRequestMethod("POST");
conn.setRequestProperty("Connection", "Keep-Alive");
conn.setRequestProperty("ENCTYPE", "multipart/form-data");
conn.setRequestProperty("Content-Type", "multipart/form-data;boundary=" + boundary);
conn.setRequestProperty("uploaded_file", fileName);
List<NameValuePair> params = new ArrayList<NameValuePair>();
params.add(new BasicNameValuePair("journey_id", Integer.toString(journey_id)));
params.add(new BasicNameValuePair("task_id", Integer.toString(task_id)));
OutputStream os = conn.getOutputStream();
BufferedWriter writer = new BufferedWriter(new OutputStreamWriter(os, "UTF-8"));
writer.write(getQuery(params));
dos = new DataOutputStream(os);
dos.writeBytes(twoHyphens + boundary + lineEnd);
dos.writeBytes("Content-Disposition: form-data; name=\"uploaded_file\";filename=\""
+ fileName + "\"" + lineEnd);
dos.writeBytes(lineEnd);
// create a buffer of maximum size
bytesAvailable = fileInputStream.available();
bufferSize = Math.min(bytesAvailable, maxBufferSize);
buffer = new byte[bufferSize];
// read file and write it into form...
bytesRead = fileInputStream.read(buffer, 0, bufferSize);
while (bytesRead > 0) {
dos.write(buffer, 0, bufferSize);
bytesAvailable = fileInputStream.available();
bufferSize = Math.min(bytesAvailable, maxBufferSize);
bytesRead = fileInputStream.read(buffer, 0, bufferSize);
}
// send multipart form data necesssary after file data...
dos.writeBytes(lineEnd);
dos.writeBytes(twoHyphens + boundary + twoHyphens + lineEnd);
// Responses from the server (code and message)
serverResponseCode = conn.getResponseCode();
String serverResponseMessage = conn.getResponseMessage();
Log.d("serverResponseMessage", serverResponseMessage);
Log.i("uploadFile", "HTTP Response is : "
+ serverResponseMessage + ": " + serverResponseCode);
if(serverResponseCode == 200){
return "Photo successfully uploaded";
}
//close the streams //
fileInputStream.close();
dos.flush();
dos.close();
} catch (Exception e) {
e.printStackTrace();
}
return "Oops! An error occurred";
}
}
private String getQuery(List<NameValuePair> params) throws UnsupportedEncodingException
{
StringBuilder result = new StringBuilder();
boolean first = true;
for (NameValuePair pair : params)
{
if (first)
first = false;
else
result.append("&");
result.append(URLEncoder.encode(pair.getName(), "UTF-8"));
result.append("=");
result.append(URLEncoder.encode(pair.getValue(), "UTF-8"));
}
return result.toString();
}
<?php
$file_path = "uploads/";
$journey_id = $_GET["journey_id"];
$task_id = $_GET["task_id"];
$file_path = $file_path . basename( $_FILES['uploaded_file']['name']);
if(move_uploaded_file($_FILES['uploaded_file']['tmp_name'], $file_path)) {
$con = mysqli_connect("localhost","db_user","somepassword","mydb");
$result = mysqli_query($con, "UPDATE journey_task_pairs SET image_name = '".$_FILES['uploaded_file']['tmp_name']."', image_path = '".$file_path."' WHERE journey_id = $journey_id && task_id = $task_id");
mysqli_close($con);
} else{
echo "fail";
}
?>