Ich schreibe erfolgreich die Textdatei von (json_string) in den internen Speicher von Android-Handy, aber die gleiche Datei, die ich auf PHP-Server schreibe, wird leer hochgeladen. Bitte sehen Sie meinen Code unten und lassen Sie mich wissen, wo liege ich falsch? Bitte helfen Sie mir Ich bin neu in PHP und Android.Schreiben Sie eine Textdatei auf den PHP-Server von Android erstellt leere Textdatei?
public class MainActivity extends AppCompatActivity {
private static final String TAG = "MainActivity.java";
private static final int SURVEY_REQUEST = 1337;
private static final int REQUEST_EXTERNAL_STORAGE = 1;
private static String[] PERMISSIONS_STORAGE = {
Manifest.permission.READ_EXTERNAL_STORAGE,
Manifest.permission.WRITE_EXTERNAL_STORAGE
};
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
if (android.os.Build.VERSION.SDK_INT > 9) {
StrictMode.ThreadPolicy policy = new StrictMode.ThreadPolicy.Builder().permitAll().build();
StrictMode.setThreadPolicy(policy);
}
verifyStoragePermissions(this); // for permission in marshallow and up operating system
//buttons
Button button_survey_example_1 = (Button) findViewById(R.id.button_survey_example_1);
button_survey_example_1.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
Intent i_survey = new Intent(MainActivity.this, SurveyActivity.class);
//you have to pass as an extra the json string.
i_survey.putExtra("json_survey", loadSurveyJson("feedback1.json"));
startActivityForResult(i_survey, SURVEY_REQUEST);
}
});
}
public static void verifyStoragePermissions(Activity activity) {
// Check if we have read or write permission
int writePermission = ActivityCompat.checkSelfPermission(activity, Manifest.permission.WRITE_EXTERNAL_STORAGE);
int readPermission = ActivityCompat.checkSelfPermission(activity, Manifest.permission.READ_EXTERNAL_STORAGE);
if (writePermission != PackageManager.PERMISSION_GRANTED || readPermission != PackageManager.PERMISSION_GRANTED) {
// We don't have permission so prompt the user
ActivityCompat.requestPermissions(
activity,
PERMISSIONS_STORAGE,
REQUEST_EXTERNAL_STORAGE
);
}
}
@Override
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
File file = null;
if (requestCode == SURVEY_REQUEST) {
if (resultCode == RESULT_OK) {
String answers_json = data.getExtras().getString("answers");
Log.d("****", "****************** WE HAVE ANSWERS ******************");
final int v = Log.v("ANSWERS JSON", answers_json);
Log.d("****", "*****************************************************");
final File path =
Environment.getExternalStoragePublicDirectory
(
//Environment.DIRECTORY_PICTURES
Environment.DIRECTORY_DOWNLOADS + "/QA/"
);
if (!path.exists()) {
// Make it, if it doesn't exit
path.mkdirs();
}
Date date = new Date();
file = new File(path, date + ".txt");
JsonFlattener parser = new JsonFlattener();
CSVWriter writer = new CSVWriter();
List<Map<String, String>> flatJson = null;
try {
flatJson = parser.parseJson(answers_json);
} catch (Exception e) {
e.printStackTrace();
}
try {
writer.writeAsCSV(flatJson, path + " " + date + ".csv");
// file = new File(path, date + ".csv");
} catch (FileNotFoundException e) {
e.printStackTrace();
}
try {
file.createNewFile();
FileOutputStream fOut = new FileOutputStream(file);
OutputStreamWriter myOutWriter = new OutputStreamWriter(fOut);
myOutWriter.append(answers_json);
MultipartEntityBuilder builder = MultipartEntityBuilder.create();
builder.setMode(HttpMultipartMode.BROWSER_COMPATIBLE);
FileBody fileBody = new FileBody(file);
builder.addPart("file", fileBody);
HttpEntity reqEntity = builder.build();
URL url = null;
try {
url = new URL("http://localhost/UploadToServer.php");
} catch (MalformedURLException e) {
e.printStackTrace();
}
HttpURLConnection conn = null;
try {
conn = (HttpURLConnection) url.openConnection();
} catch (IOException e) {
e.printStackTrace();
}
conn.setReadTimeout(10000);
conn.setConnectTimeout(15000);
conn.setRequestMethod("POST");
conn.setUseCaches(false);
conn.setDoInput(true);
conn.setDoOutput(true);
conn.setRequestProperty("Connection", "Keep-Alive");
conn.addRequestProperty("Content-length", reqEntity.getContentLength()+"");
conn.addRequestProperty(reqEntity.getContentType().getName(), reqEntity.getContentType().getValue());
OutputStream os = conn.getOutputStream();
reqEntity.writeTo(conn.getOutputStream());
os.flush();
os.close();
conn.connect();
if (conn.getResponseCode() == HttpURLConnection.HTTP_OK) {
Log.d("UPLOAD", "HTTP 200 OK.");
return readStream(conn.getInputStream(In));
This return returns the response from the upload.
} else {
Log.d("UPLOAD", "HTTP "+conn.getResponseCode()+" "+conn.getResponseMessage()+".");
String stream = readStream(conn.getInputStream());
Log.d("UPLOAD", "Response: "+stream);
return stream;
}
AlertDialog.Builder dlgAlert = new AlertDialog.Builder(this, R.style.MyDialogTheme);
dlgAlert.setMessage("Thank you for your time");
dlgAlert.setTitle("QA APP");
dlgAlert.setPositiveButton("Ok", null);
dlgAlert.setCancelable(true);
dlgAlert.create().show();
myOutWriter.close();
fOut.flush();
fOut.close();
} catch (IOException e) {
Log.e("Exception", "File write failed: " + e.toString());
}
}
}
}
Und mein PHP-Code ist
<?php
$name = $_FILES['file']['name'];
$temp_name = $_FILES['file']['tmp_name'];
if(isset($name)){
if(!empty($name)){
$location = 'upload/';
if(move_uploaded_file($temp_name, $location.$name)){
echo 'File uploaded successfully';
}
}
}
else {
echo 'failed !!';
}
?>
versuchen Sie, Retrofit2 zu verwenden, um mit dem Server zu kommunizieren https://square.github.io/retrofit/ –
Vielen Dank für Ihren Vorschlag. Aus dem obigen Code kann ich eine TXT-Datei ohne Datenverlust in den internen Speicher schreiben. aber das gleiche passiert nicht mit Server, Datei erstellt, aber leer. wenn ich die bereits erstellte txt-datei von android gebe, wird sie hochgeladen. – user1768942