android - Upload a text file through POST request method to a server with PHP script has issue with Unicode characters in the uploaded file
Get the solution ↓↓↓In an Android application,
I use the following code to upload a txt file to server withPOST
request method:
public static String ServiceCall_TextCommand(String mFileName, String mFileDestination, String mFileData)
{
int serverResponseCode = 0;
String fileName = mFileName;
String upLoadServerUri = null;
/************* Php script path ****************/
upLoadServerUri = mFileDestination;
HttpURLConnection conn = null;
DataOutputStream dos = null;
String lineEnd = "\r\n";
String twoHyphens = "--";
String boundary = "*****";
int bytesRead, bytesAvailable, bufferSize;
byte[] buffer;
int maxBufferSize = 5 * 1024 * 1024;
try {
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);
dos = new DataOutputStream(conn.getOutputStream());
dos.writeBytes(twoHyphens + boundary + lineEnd);
dos.writeBytes("Content-Disposition: form-data; name=\"uploaded_file\"; filename=\""
+ fileName + "\"" + lineEnd);
dos.writeBytes(lineEnd);
bufferSize = mFileData.length();
buffer = mFileData.getBytes(Charset.forName("UTF-8"));
dos.write(buffer, 0, bufferSize);
dos.writeBytes(lineEnd);
dos.writeBytes(twoHyphens + boundary + twoHyphens + lineEnd);
// Responses from the server (code and message)
serverResponseCode = conn.getResponseCode();
String serverResponseMessage = conn.getResponseMessage();
Log.i("BBBuploadFile", "HTTP Response is : "
+ serverResponseMessage + ": " + serverResponseCode);
if (serverResponseCode == 200) {
Log.e(TAG, "Complete");
}
else
{
return Constants.ServerResponse_Error_General;
}
BufferedReader in = new BufferedReader(new InputStreamReader(conn.getInputStream()));
StringBuilder total = new StringBuilder();
String line;
while ((line = in.readLine()) != null)
{
total.append(line).append('\n');
}
dos.flush();
dos.close();
// Verify Command Response Checksum
String mServerResponse = total.toString();
mServerResponse = getStringBetween(mServerResponse,"@#@","#@#");
return mServerResponse;
} catch (MalformedURLException ex) {
ex.printStackTrace();
Log.e("Upload file to server", "error: " + ex.getMessage(), ex);
return Constants.ServerResponse_Error_General;
} catch (Exception e) {
e.printStackTrace();
Log.e(TAG, "111Exception: " + e.getMessage());
return Constants.ServerResponse_Error_General;
}
}
And the server side PHP code is as following:
<?php
header('Content-type: text/plain');
require_once $ServerRoot.'/HandleUploadedFile/HandleUploadedFile.php';
use HandleUploadedFile\HandleUploadedFile_Status;
print "\nFile Received, Root: {$_SERVER['DOCUMENT_ROOT']}\nName: {$_FILES['uploaded_file']['name']}\nSize: {$_FILES['uploaded_file']['size']}";
echo "\nprint_r:\n";
print_r($_FILES);
$mClass_HandleUploadedFile_Status = new HandleUploadedFile_Status();
if ($mClass_HandleUploadedFile_Status->IsUploadedFileValid() === true)
{
echo "\File is valid\n";
echo "\nupload successful";
$File_Name = $_FILES['uploaded_file']['name'];
$File_SplitName = explode(".", $File_Name);
$File_Name_NoExtension = $File_SplitName[0];
$File_Extension = end($File_SplitName);
$ReadFile_Resource = fopen($_FILES['uploaded_file']['tmp_name'], "r");
$ReadFile = fread($ReadFile_Resource, filesize($_FILES['uploaded_file']['tmp_name']));
$fz = filesize($_FILES['uploaded_file']['tmp_name']);
echo "\n*#*\nfz :\n{$fz}\n#*###\n";
echo "\n\nReadFile :\n{$ReadFile}\n\n";
fclose($ReadFile_Resource);
}
And
<?php
namespace HandleUploadedFile;
class HandleUploadedFile_Status
{
public function IsUploadedFileValid()
{
if($this->UploadedFileExists() === true)
{
if($this->UploadedFileKeyArrayExists() === true)
{
if($this->UploadedFileIsErrorOk() === true)
{
return true;
}
else
{
return false;
}
}
else
{
return false;
}
}
else
{
return false;
}
}
public function UploadedFileExists()
{
if(isset($_FILES["uploaded_file"]))
{
return true;
}
else
{
return false;
}
}
public function UploadedFileKeyArrayExists()
{
if(array_key_exists('uploaded_file', $_FILES))
{
return true;
}
else
{
return false;
}
}
public function UploadedFileIsErrorOk()
{
if($_FILES['uploaded_file']['error'] === UPLOAD_ERR_OK)
{
return true;
}
else
{
return false;
}
}
}
mFileData to be uploaded from Android Application is as following:
ED1235bkoala02PKKKKKKaKKKKKKKKbzG^{"P":[{"a":"0f","b":"01q","c":"X","d":"Y"}]}^A
As there is no Unicode letter in the above data, there is no problem and everything is allright
Question:
When I add a Unicode letter"Щ€"
instead of"X"
, then the$ReadFile
in PHP does not contain the last letter(A)
:
ED1235bkoala02PKKKKKKaKKKKKKKKbzG^{"P":[{"a":"0f","b":"01q","c":"Щ€","d":"Y"}]}^A
In other words,
it seems sinceUTF-8
of"Щ€"
is 2 bytes, then PHP misunderstands and counts just 1 character and so the last character(A)
is not read with the above code
Again if I replace"Щ€"
with"Щ€Ъ©"
the the last 2 characters(^A)
are not read this time and so on
It is definitely something related toUTF-8
encoding but I can't get a trueUTF-8
data in PHP code even if I send it from Android Application
Share solution ↓
Additional Information:
Link To Answer People are also looking for solutions of the problem: warning: undefined array key
Didn't find the answer?
Our community is visited by hundreds of web development professionals every day. Ask your question and get a quick answer for free.
Similar questions
Find the answer in similar questions on our website.
Write quick answer
Do you know the answer to this question? Write a quick response to it. With your help, we will make our community stronger.