2011-11-29 80 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; 
      } 
     }