So I have done this earlier multiple times using the MultiPartEntity in apache implementations but now with the deprecation of the APIs I need to use HTTPUrlConnection.
My Server side script looks something like this in php
$userData = urldecode ( $_POST['form'] );
$json = json_decode ( $userData );
$username = $json->emailAddress;
$this->load->model( 'rest_image_upload_model' );
$result = $this->rest_image_upload_model->checkCredentialsAndReturnUserId ($username, $password);
$userId = $result ['mfwid'];
if($userId == 0 || empty($userId) || false == $result){
$responseJson['success'] = false;
$responseJson['message'] = "Username could not be fetched. Contact system admin.";
echo json_decode($responseJson);
return;
}
$firstName = '';
$result = $this->rest_image_upload_model->fetchUsersName( $userId );
$firstName = $result ['first_name'];
if(empty($firstName) || false == $result){
$responseJson['success'] = false;
$responseJson['message'] = "First Name could not be fetched. Contact system admin.";
echo json_decode($responseJson);
return;
}
//end of json part
// Start creating a floder for the image to be uploaded
$foldername = $firstName . '-' . $userId;
if (! is_dir ( 'download/upload/profile/' . $date . '/' . $foldername )){
mkdir ( './download/upload/profile/' . $date . '/' . $foldername, 0777, TRUE );
}
$config ['upload_path'] = './download/upload/profile/' . $date . '/' . $foldername;
$thumbnailRefFilePath = $config['upload_path'];
$config ['allowed_types'] = "jpg|png|JPEG|jpeg|PNG|JPG"; // 'gif|jpg|png|tiff';
$config ['max_size'] = '10240';
$config ['max_width'] = '5000';
$config ['max_height'] = '5000';
$this->load->library ( 'upload', $config );
$this->upload->initialize ( $config );
if (! $this->upload->do_upload ( 'image' )) { // if uploading image failed
$responseJson['success'] = false;
$responseJson['message'] = "File Not Uploaded";
//$upload_data['file_name']='nopic.png';
echo json_encode($responseJson);
return;
} else {
// uploading image success
$upload_data = $this->upload->data(); // save
}
The Android code seems to upload the json part but I get the error. File not uploaded in a json. Below is my android code for this.
public StringBuilder doMultipartPost(String api,
String jsonPost,
String jsonPartKey,
String filePath,
String filePathKey) throws InstyreNetworkException{
String boundary = UUID.randomUUID().toString();
String twoHyphens = "--";
//String attachmentName = "data";
String crlf = "\r\n";
int bytesRead, bytesAvailable, bufferSize;
byte[] buffer;
int maxBufferSize = 1 * 1024 * 1024;
try {
final String URL = NetworkUtils.BASE_URL + api;
URI uri = new URI(URL);
HttpURLConnection urlConnection = (HttpURLConnection) uri.toURL().openConnection();
urlConnection.setRequestMethod("POST");
urlConnection.setRequestProperty("Connection", "Keep-Alive");
urlConnection.setDoInput(true);
urlConnection.setDoOutput(true);
urlConnection.setRequestProperty("Content-Type", "multipart/form-data;boundary=" + boundary);
DataOutputStream dos = new DataOutputStream(urlConnection.getOutputStream());
// FIRST PART; A JSON object
dos.writeBytes(twoHyphens + boundary);
dos.writeBytes(crlf);
dos.writeBytes("Content-Type: application/json");
dos.writeBytes(crlf);
dos.writeBytes("Content-Disposition: form-data; name=\""+jsonPartKey+"\"");
dos.writeBytes(crlf);
dos.writeBytes(crlf);
dos.writeBytes(jsonPost);
dos.writeBytes(crlf);
// SECOND PART; A image..
File file = new File(filePath);
FileInputStream fileInputStream = new FileInputStream(file);
dos.writeBytes(twoHyphens + boundary);
dos.writeBytes(crlf);
dos.writeBytes("Content-Type: jpg");
dos.writeBytes(crlf);
dos.writeBytes("Content-Disposition: form-data; name=\"image\"");
// dos.writeBytes("Content-Disposition: form-data; name=\"attachment_0\";filename=\"" + file.getName() + "\"" + lineEnd);
dos.writeBytes(crlf);
dos.writeBytes(crlf);
dos.writeBytes("Content-Length: " + file.length() + crlf);
dos.writeBytes(crlf);
dos.writeBytes(crlf);
bytesAvailable = fileInputStream.available();
bufferSize = Math.min(bytesAvailable, maxBufferSize);
buffer = new byte[bufferSize];
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);
}
dos.writeBytes(crlf);
dos.writeBytes(twoHyphens + boundary + crlf);
fileInputStream.close();
// start reading response
InputStream is = urlConnection.getInputStream();
BufferedReader streamReader = new BufferedReader(new InputStreamReader(is, "UTF-8"));
StringBuilder responseStrBuilder = new StringBuilder();
String inputStr;
while ((inputStr = streamReader.readLine()) != null)
responseStrBuilder.append(inputStr);
is.close();
dos.close();
} catch (Exception e) {
e.printStackTrace();
}
return null;
}
You did not select a file to upload.
"} – ichthyocentaurs Sep 03 '15 at 21:10