I konw this has been asked a couple of times in this site but I could not find a correct way to do it.
I want to upload a file from android to server using HTTPURLCONNECTION and PHP. I found tutorial on it but only in sending the file not with data. data includes file name, details/description and comments.
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);
conn.setRequestProperty("Filename","testfilename");
JSONObject cred = new JSONObject();
cred.put("name","juan");
cred.put("password","pass");
dos = new DataOutputStream(conn.getOutputStream());
// for every param
dos.writeBytes("Content-Disposition: form-data; name=\"chunk\"" + lineEnd);
dos.writeBytes("Content-Type: text/plain; charset=UTF-8" + lineEnd);
dos.writeBytes("Content-Length: " + cred.length() + lineEnd);
dos.writeBytes(lineEnd);
dos.writeBytes(cred.toString() + lineEnd);
dos.writeBytes(twoHyphens + boundary + lineEnd);
/**Create file*/
dos.writeBytes(twoHyphens + boundary + lineEnd);
dos.writeBytes (cred.toString());
dos.writeBytes("Content-Disposition: form-data; name=\"uploaded_file\";filename=\""
+ fileName + "\"" + lineEnd);
dos.writeBytes(lineEnd); //close the streams //
fileInputStream.close();
dos.flush();
dos.close();
and in my php :
$name=$this->input->post('name');
$headers = $this->input->request_headers();
// print_r('sample result: - '.$headers['Filename']);
$file_name = $headers['Filename'];
$config2['upload_path'] = 'cms/uploads/reports_images/';
$config2['allowed_types'] = 'jpg|png|xls';
$config2['max_size'] = '2048';
$config2['file_name'] = $file_name.'_'.date('Y_m_d_H_i_s',time());
$this->load->library('upload',$config2);
$this->upload->initialize($config2);
echo "name ".'-'.$name;
// $file_path = $file_path . basename( $_FILES['uploaded_file']['file_name']);
if($this->upload->do_upload('uploaded_file')) {
echo "success".'-'.$name;
} else{
echo "fail";
print_r($this->upload->display_errors());
}
but tried to print the response in the log cat and this is what i got
HTTP Response is : name -fail
You did not select a file to upload.
How should it be done correctly?
Thanks for your help.
0 comments:
Post a Comment