从Android写一个文本文件到PHP服务器创建空白文本文件?

时间:2017-06-02 09:36:02

标签: php android

我成功地将文本文件从(json_string)写入Android手机的内部存储器,但是我写给PHP服务器的同一文件正在上传空白。请看下面的代码,让我知道我哪里错了?请帮助我,我是PHP和Android的新手。

    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());
                }






            }
        }
    }

我的PHP代码是

      <?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 !!';
    }
?>

1 个答案:

答案 0 :(得分:0)

我做到了。在我开始连接之前,我必须刷新OutStreamWriter

  file.createNewFile();
                FileOutputStream fOut = new FileOutputStream(file);
                OutputStreamWriter myOutWriter = new OutputStreamWriter(fOut);
                myOutWriter.append(answers_json);


                myOutWriter.close();

                fOut.flush();
                fOut.close();

现在它完全正常工作。感谢您使用此平台。