如何在Android中使用PHP将PDF文件上传到服务器?

问题描述:

我正尝试在Android中使用PHP将PDF文件上传到服务器。为此,我获取所选文件的URI并将这些数据发布到我的服务器中的PHP文件中。这是我发布的数据:如何在Android中使用PHP将PDF文件上传到服务器?

URL url = new URL(url_path); 
conn = (HttpURLConnection) url.openConnection(); 
conn.setDoOutput(true); 
conn.setUseCaches(false); 
conn.setDoInput(true); 
conn.setChunkedStreamingMode(1024); 
conn.setRequestMethod("POST"); 
conn.setRequestProperty("Connection", "Keep-Alive"); 
conn.setRequestProperty("Content-Type", "multipart/form-data"); 

OutputStream outputStream = conn.getOutputStream(); 
InputStream inputStream = c.getContentResolver().openInputStream(path); 
Log.e("URI",path.toString()); 
int bytesAvailable = inputStream.available(); 
int bufferSize = Math.min(bytesAvailable, maxBufferSize); 
byte[] buffer = new byte[bufferSize]; 
int bytesRead; 
while ((bytesRead = inputStream.read(buffer, 0, bufferSize)) != -1) { 
    outputStream.write(buffer, 0, bytesRead); 
} 
Log.e("URI",String.valueOf(bytesAvailable)); 
outputStream.flush(); 
inputStream.close(); 

该数据发布到这个PHP文件:

<?php 
print_r($_REQUEST); 
$file_name = date("U").".pdf"; 
$server_path = "uploads/"; 
$web_path = "http://mysite/uploads/"; 

$file = $server_path.$file_name; 
file_put_contents($file,""); 

$fp = fopen("php://input",'r'); 
echo 'fp : '.$fp; 
while ($buffer = fread($fp,8192)){ 
    echo $buffer; 
    file_put_contents($file,$buffer,FILE_APPEND | LOCK_EX); 
}?> 

对于每个上载,它会在我的上传目录中的新文件。但PDF的大小是0字节。我不知道为什么。请帮助我。提前致谢。

+0

更改文件为base64并发送文本到php文件。 – 2017-03-01 20:15:06

+0

@Breakermind你可以给我一个链接的例子吗? – Choxmi

+0

http://*.com/questions/10226046/java-convert-image-to-base64 – 2017-03-01 20:16:47

<?php 

    $file_path = "uploads/"; 

    $file_path = $file_path . basename($_FILES['uploaded_file']['name']); 
    if(move_uploaded_file($_FILES['uploaded_file']['tmp_name'], $file_path)){ 
     echo "success"; 
    } else{ 
     echo "fail"; 
    } 
?> 

public int uploadFile(final String selectedFilePath){ 

    int serverResponseCode = 0; 

    HttpURLConnection connection; 
    DataOutputStream dataOutputStream; 
    String lineEnd = "\r\n"; 
    String twoHyphens = "--"; 
    String boundary = "*****"; 


    int bytesRead,bytesAvailable,bufferSize; 
    byte[] buffer; 
    int maxBufferSize = 1 * 1024 * 1024; 
    File selectedFile = new File(selectedFilePath); 


    String[] parts = selectedFilePath.split("/"); 
    final String fileName = parts[parts.length-1]; 

    if (!selectedFile.isFile()){ 
     dialog.dismiss(); 

     runOnUiThread(new Runnable() { 
      @Override 
      public void run() { 
       tvFileName.setText("Source File Doesn't Exist: " + selectedFilePath); 
      } 
     }); 
     return 0; 
    }else{ 
     try{ 
      FileInputStream fileInputStream = new FileInputStream(selectedFile); 
      URL url = new URL(SERVER_URL); 
      connection = (HttpURLConnection) url.openConnection(); 
      connection.setDoInput(true);//Allow Inputs 
      connection.setDoOutput(true);//Allow Outputs 
      connection.setUseCaches(false);//Don't use a cached Copy 
      connection.setRequestMethod("POST"); 
      connection.setRequestProperty("Connection", "Keep-Alive"); 
      connection.setRequestProperty("ENCTYPE", "multipart/form-data"); 
      connection.setRequestProperty("Content-Type", "multipart/form-data;boundary=" + boundary); 
      connection.setRequestProperty("uploaded_file",selectedFilePath); 

      //creating new dataoutputstream 
      dataOutputStream = new DataOutputStream(connection.getOutputStream()); 

      //writing bytes to data outputstream 
      dataOutputStream.writeBytes(twoHyphens + boundary + lineEnd); 
      dataOutputStream.writeBytes("Content-Disposition: form-data; name=\"uploaded_file\";filename=\"" 
        + selectedFilePath + "\"" + lineEnd); 

      dataOutputStream.writeBytes(lineEnd); 

      //returns no. of bytes present in fileInputStream 
      bytesAvailable = fileInputStream.available(); 
      //selecting the buffer size as minimum of available bytes or 1 MB 
      bufferSize = Math.min(bytesAvailable,maxBufferSize); 
      //setting the buffer as byte array of size of bufferSize 
      buffer = new byte[bufferSize]; 

      //reads bytes from FileInputStream(from 0th index of buffer to buffersize) 
      bytesRead = fileInputStream.read(buffer,0,bufferSize); 

      //loop repeats till bytesRead = -1, i.e., no bytes are left to read 
      while (bytesRead > 0){ 
       //write the bytes read from inputstream 
       dataOutputStream.write(buffer,0,bufferSize); 
       bytesAvailable = fileInputStream.available(); 
       bufferSize = Math.min(bytesAvailable,maxBufferSize); 
       bytesRead = fileInputStream.read(buffer,0,bufferSize); 
      } 

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

      serverResponseCode = connection.getResponseCode(); 
      String serverResponseMessage = connection.getResponseMessage(); 

      Log.i(TAG, "Server Response is: " + serverResponseMessage + ": " + serverResponseCode); 

      //response code of 200 indicates the server status OK 
      if(serverResponseCode == 200){ 
       runOnUiThread(new Runnable() { 
        @Override 
        public void run() { 
         tvFileName.setText("File Upload completed.\n\n You can see the uploaded file here: \n\n" + "http://coderefer.com/extras/uploads/"+ fileName); 
        } 
       }); 
      } 

      //closing the input and output streams 
      fileInputStream.close(); 
      dataOutputStream.flush(); 
      dataOutputStream.close(); 



     } catch (FileNotFoundException e) { 
      e.printStackTrace(); 
      runOnUiThread(new Runnable() { 
       @Override 
       public void run() { 
        Toast.makeText(MainActivity.this,"File Not Found",Toast.LENGTH_SHORT).show(); 
       } 
      }); 
     } catch (MalformedURLException e) { 
      e.printStackTrace(); 
      Toast.makeText(MainActivity.this, "URL error!", Toast.LENGTH_SHORT).show(); 

     } catch (IOException e) { 
      e.printStackTrace(); 
      Toast.makeText(MainActivity.this, "Cannot Read/Write File!", Toast.LENGTH_SHORT).show(); 
     } 
     dialog.dismiss(); 
     return serverResponseCode; 
    } 

} 

编号:http://www.coderefer.com/android-upload-file-to-server/https://github.com/vamsitallapudi/AndroidUploadFileToServer

+0

这里失败了'!selectedFile.isFile()'。我从'ACTION_GET_CONTENT'的onactivity结果中获得路径。为什么Uri在这里失败? – Choxmi

+0

我建议您使用翻新来上传文件。 –

而不是做自己,你可以很容易地使用这个库名为ION:https://github.com/koush/ion。上传PDF文件简单如下:

Ion.with(getContext()) 
.load("your url") 
.setMultipartFile("archive", "application/pdf", new File("path to file")) 
.setCallback(...) 

最好的方法是使用Retrofit代替。这里是一个示例应用程序,您可以使用:https://github.com/hidrodixtion/Example-Retrofit-Image-Upload

+0

我会尝试改造。非常感谢。 – Choxmi