2017-06-02 43 views
-1

我正在成功將文本文件從(json_string)寫入Android手機的內部存儲器,但是我正在寫入PHP服務器的相同文件正在上傳空白。請參閱下面的代碼,讓我知道我錯在哪裏?請幫助我我是PHP和Android的新手。從Android寫入文本文件到PHP服務器正在創建空白文本文件?

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

嘗試使用retrofit2以便與服務器通信https://square.github.io/retrofit/ –

+0

感謝您的建議。從上面的代碼中,我可以將txt文件寫入內部存儲,而不會丟失數據。但服務器沒有發生同樣的情況,文件正在創建,但空的。如果我從android中指定已經創建的txt文件,那麼它正在上傳。 – user1768942

回答

0

我做到了人。在我開始連接之前,我必須沖洗OutStreamWriter

​​

現在它工作的很好。感謝您的這個平臺。