2011-11-29 83 views
1

我想寫一個文件並上傳它,但是,該文件似乎沒有被正確寫入(後來我需要上傳它,它崩潰,並說沒有文件)。我遵循Google的documentation的指導原則。這裏是我的代碼:Android寫入文件

String fileLocation = "Hello"; 
    String TESTSTRING = new String("Hello Android"); 

    FileOutputStream fOut = openFileOutput(fileLocation, MODE_WORLD_READABLE); 

    fOut.write(TESTSTRING.getBytes()); 
    fOut.close(); 

這就是我正在嘗試上傳:

HttpURLConnection connection = null; 
    DataOutputStream outputStream = null; 
    DataInputStream inputStream = null; 

    String pathToOurFile = fileLocation; 

    String Tag = "UPLOADER"; 
    HttpURLConnection conn = null; 



    String urlServer = "http://..."; //my server 
     String lineEnd = "\r\n"; 
     String twoHyphens = "--"; 
     String boundary = "*****"; 
     try { 
      // ------------------ CLIENT REQUEST 

      Log.e(Tag, "Inside second Method"); 

      FileInputStream fileInputStream = new FileInputStream(new File(fileLocation)); 
      // open a URL connection to the Servlet 
      URL url = new URL(urlServer); 
      // Open a HTTP connection to the URL 
      conn = (HttpURLConnection) url.openConnection(); 
      // Allow Inputs 
      conn.setDoInput(true); 
      // Allow Outputs 
      conn.setDoOutput(true); 
      // Don't use a cached copy. 
      conn.setUseCaches(false); 
      // Use a post method. 
      conn.setRequestMethod("POST"); 

      conn.setRequestProperty("Connection", "Keep-Alive"); 

      conn.setRequestProperty("Content-Type", "multipart/form-data;boundary=" + boundary); 

      DataOutputStream dos = new DataOutputStream(conn.getOutputStream()); 

      dos.writeBytes(twoHyphens + boundary + lineEnd); 
      dos 
        .writeBytes("Content-Disposition: post-data; name=uploadedfile;filename=" 
          + fileLocation + "" + lineEnd); 
      dos.writeBytes(lineEnd); 

      Log.e(Tag, "Headers are written"); 

      // create a buffer of maximum size 

      int bytesAvailable = fileInputStream.available(); 
      int maxBufferSize = 1000; 
      // int bufferSize = Math.min(bytesAvailable, maxBufferSize); 
      byte[] buffer = new byte[bytesAvailable]; 

      // read file and write it into form... 

      int bytesRead = fileInputStream.read(buffer, 0, bytesAvailable); 

      while (bytesRead > 0) { 
       dos.write(buffer, 0, bytesAvailable); 
       bytesAvailable = fileInputStream.available(); 
       bytesAvailable = Math.min(bytesAvailable, maxBufferSize); 
       bytesRead = fileInputStream.read(buffer, 0, bytesAvailable); 
      } 

      // send multipart form data necesssary after file data... 

      dos.writeBytes(lineEnd); 
      dos.writeBytes(twoHyphens + boundary + twoHyphens + lineEnd); 

      // close streams 
      Log.e(Tag, "File is written"); 
      fileInputStream.close(); 
      dos.flush(); 
      dos.close(); 

     } catch (MalformedURLException ex) { 
      Log.e(Tag, "error: " + ex.getMessage(), ex); 
     } 

     catch (IOException ioe) { 
      Log.e(Tag, "error: " + ioe.getMessage(), ioe); 
     } 

     try { 
      BufferedReader rd = new BufferedReader(new InputStreamReader(conn.getInputStream())); 
      String line; 
      while ((line = rd.readLine()) != null) { 
       Log.e("Dialoge Box", "Message: " + line); 
      } 
      rd.close(); 

     } catch (IOException ioex) { 
      Log.e("MediaPlayer", "error: " + ioex.getMessage(), ioex); 
     } 
    } 

這裏的服務器上的PHP代碼:

$target_path = "./"; 
$target_path = $target_path . basename($_FILES['uploadedfile']['name']); 
if(move_uploaded_file($_FILES['uploadedfile']['tmp_name'], $target_path)) { 
echo "The file ". basename($_FILES['uploadedfile']['name']). 
" has been uploaded"; 
} else{ 
echo "There was an error uploading the file, please try again!"; 
} 
+0

它是否例外? – gigadot

+0

哪部分崩潰,寫入文件或讀取文件? – gyoda

+0

@ gigadot不,它不。 – Tring

回答

2

而不是使用

FileInputStream fileInputStream = new FileInputStream(new File(fileLocation)); 

使用

FileInputStream fileInputStream = openFileInput(fileLocation); 
+0

謝謝!它不再崩潰,但是,該文件仍未上傳。你能看看代碼嗎?我已經用服務器的PHP代碼更新了第一篇文章。 – Tring

+0

我不是一個真正的PHP傢伙,所以我將不得不傳遞那一個。我建議用PHP代碼打開一個新問題,因爲這個問題實際上是關於Android文件寫入/閱讀的。並接受我的答案,如果它幫助你了;) – gyoda

+0

當然!再次感謝。 – Tring

0

嘗試這樣:

fileLocation = context.getFilesDir() + "Hello"; 

我不知道,你可以/應該文件寫入到根目錄這樣。

+0

感謝喬,我認爲它寫入我的應用程序本地存儲(而不是根)。無論如何,問題是讀回來,而不是寫作。它現在解決了! – Tring

0

請先寫一個像這樣的字符串,然後再發送文件到服務器。它會幫助一些人。

 String resp = "Hello Andrid!!!"; 
     File file= new File("/sdcard/hello.xml");       
     FileOutputStream fos = new FileOutputStream(file); 

     try { 
      fos.write(resp.getBytes()); 
      fos.flush(); 
      fos.close();     
      Log.d("File Write is success","fine"); 
     } catch (Exception e) { 
      Log.d("Error in File write: ", ""+e.getMessage()); 
     } finally { 
      if (fos != null) { 
       fos = null; 
      } 
     }