【问题标题】:Android (Java) file upload to PHP servar fails with Android 4.03Android (Java) 文件上传到 PHP servar 失败,Android 4.03
【发布时间】:2012-02-07 09:02:12
【问题描述】:

我们已经成功地为我们的游戏使用了一个脚本,该脚本连接到一个 php 文件,以便将文件上传到远程服务器。当我们升级到 Android 4.03 时,脚本突然无法连接到服务器,我们不知道为什么。它适用于 Android 2.3.4 及更早版本。

public static String uploadOrderFile(Context c) {
String error = "";

HttpURLConnection conn = null;
DataOutputStream dos = null;
DataInputStream inStream = null;
FileInputStream fileInputStream = null;

String exsistingFileName = String.format("orders%d.ser", empire.getId());
String lineEnd = "\r\n";
String twoHyphens = "--";
String boundary =  "*****";

int bytesRead, bytesAvailable, bufferSize;
byte[] buffer;
int maxBufferSize = 1*1024*1024;
String responseFromServer = "";

try {
    //------------------ CLIENT REQUEST
    // Opening streams.
    if(settings.isSaveToExternalStorage()) {
        File file = new File(Environment.getExternalStorageDirectory(), String.format("%sorders%s.ser", c.getString(R.string.pathExternalStorage), empire.getId()));
        fileInputStream = new FileInputStream(file);
    }
    else {
        fileInputStream = c.openFileInput(exsistingFileName);
    }

    // open a URL connection to the Servlet
    String s = c.getString(R.string.webPageOrders);
    URL url = new URL(s);
    // 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);

    dos = new DataOutputStream( conn.getOutputStream() );
    dos.writeBytes(twoHyphens + boundary + lineEnd);
    dos.writeBytes(String.format("Content-Disposition: form-data; name=\"uploadedfile\";filename=\"%s\"%s", exsistingFileName, lineEnd));
    dos.writeBytes(lineEnd);

    // create a buffer of maximum size
    bytesAvailable = fileInputStream.available();
    bufferSize = Math.min(bytesAvailable, maxBufferSize);
    buffer = new byte[bufferSize];

    // read file and write it into form...
    bytesRead = fileInputStream.read(buffer, 0, bufferSize);

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

    // send multipart form data necesssary after file data...
    dos.writeBytes(lineEnd);
    dos.writeBytes(twoHyphens + boundary + twoHyphens + lineEnd);
}
catch(FileNotFoundException fnfe) {
    error = "Error. Couldn't find the order file internally.";
    Log.e(TAG, error, fnfe);
}
catch (MalformedURLException murle) {
    error = "Error. Couldn't create correct file URL.";
    Log.e(TAG, error, murle);
}
catch(ProtocolException pe) {
    error = "Error. Couldn't upload the order file to server.";
    Log.e(TAG, error, pe);
}
catch (IOException ioe) {
    error = "Error. Couldn't upload the order file to server.";
    Log.e(TAG, error, ioe);
}
finally {
    try {
        // Closing streams and connections.
        if(fileInputStream != null) {
            fileInputStream.close();
        }
        if(conn != null) {
            conn.disconnect();
        }
        if(dos != null) {
            dos.flush();
            dos.close();
        }
    }
    catch(IOException ioe) {
        error = "Error. Couldn't disconnect internet stream buffers.";
        Log.e(TAG, error, ioe);
    }
}
if(!error.equals("")) {
    return error;
}
//Reading the server response.
try {
    inStream = new DataInputStream ( conn.getInputStream() );
    String str;
    while (( str = inStream.readLine()) != null) {
        responseFromServer += str;
    }
}
catch (IOException ioe){
    error = "Error. Couldn't read server response.";
    Log.e(TAG, error, ioe);
}
finally {
    try {
        // Closing streams.
        if(inStream != null) {
            inStream.close();
        }
    }
    catch(IOException ioe) {
        error = "Error. Couldn't disconnect internet stream buffers.";
        Log.e(TAG, error, ioe);
    }
}
return error;}

在服务器上,我们有以下 PHP 文件:

<?php

// Where the file is going to be placed 
$target_path = "orders/";

/* Add the original filename to our target path.  
Result is "orders/filename.extension" */
$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";
    chmod ("orders/".basename( $_FILES['uploadedfile']['name']), 0644);

} 
else{

echo "There was an error uploading the file, please try again!";
echo "filename: " .  basename( $_FILES['uploadedfile']['name']);
echo "target_path: " .$target_path;

}?>

感谢您对此问题的任何帮助。为什么它在 Android 4.03 上失败了,而它在以前的版本中运行完美?

谢谢!

【问题讨论】:

    标签: php android file-upload


    【解决方案1】:

    试试这个

    class getEditingHUD extends AsyncTask<String, Long, Integer> {
    
        protected void onPreExecute() {
            super.onPreExecute();
            loading = ProgressDialog.show(HtmlViwer.this, null,
                    "Please wait...");
        }
    
        protected Integer doInBackground(String... params) {
            File file = new File(Environment.getExternalStorageDirectory(), "yourfile.html");
            try {
                FileInputStream fis = new FileInputStream(file);
                String myserver = "http://your server/phpfile.php";
                HttpFileUploader htfu = new HttpFileUploader(myserver,
                        "noparamshere", Modules.currentProgram + ".html");
                htfu.doStart(fis);
            } catch (Exception e) {
                Log.e("Error Readingfile", e.toString());
            }
    
            return null;
        }
    
        protected void onPostExecute(Integer result) {
            super.onPostExecute(result);
            try {
                if (loading != null && loading.isShowing())
                    loading.dismiss();
            } catch (Throwable t) {
    
            }
        }
    
    }
    

    还有这个 HttpFileUploader 类

    public class HttpFileUploader implements Runnable {
    
    URL connectURL;
    String params;
    String responseString;
    // InterfaceHttpUtil ifPostBack;
    String fileName;
    byte[] dataToServer;
    
    HttpFileUploader(String urlString, String params, String fileName) {
        try {
            connectURL = new URL(urlString);
        } catch (Exception ex) {
            Log.i("URL FORMATION", "MALFORMATED URL");
        }
        this.params = params + "=";
        this.fileName = fileName;
    
    }
    
    void doStart(FileInputStream stream) {
        fileInputStream = stream;
        PrakitoServer();
    }
    
    FileInputStream fileInputStream = null;
    
    void PrakitoServer() {
        String exsistingFileName = "print.html";
    
        String lineEnd = "\r\n";
        String twoHyphens = "--";
        String boundary = "*****";
        String Tag = "3rd";
        try {
            // ------------------ CLIENT REQUEST
    
            Log.e(Tag, "Starting to bad things");
            // Open a HTTP connection to the URL
    
            HttpURLConnection conn = (HttpURLConnection) connectURL
                    .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: form-data; name=\"uploadedfile\";filename=\""
                            + exsistingFileName + "\"" + lineEnd);
            dos.writeBytes(lineEnd);
    
            Log.e(Tag, "Headers are written");
    
            // create a buffer of maximum size
    
            int bytesAvailable = fileInputStream.available();
            int maxBufferSize = 1024;
            int bufferSize = Math.min(bytesAvailable, maxBufferSize);
            byte[] buffer = new byte[bufferSize];
    
            // read file and write it into form...
    
            int bytesRead = fileInputStream.read(buffer, 0, bufferSize);
    
            while (bytesRead > 0) {
                dos.write(buffer, 0, bufferSize);
                bytesAvailable = fileInputStream.available();
                bufferSize = Math.min(bytesAvailable, maxBufferSize);
                bytesRead = fileInputStream.read(buffer, 0, bufferSize);
            }
    
            // 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();
    
            InputStream is = conn.getInputStream();
            // retrieve the response from server
            int ch;
    
            StringBuffer b = new StringBuffer();
            while ((ch = is.read()) != -1) {
                b.append((char) ch);
            }
            String s = b.toString();
            Log.i("Response", s);
            dos.close();
    
        } catch (MalformedURLException ex) {
            Log.e(Tag, "error: " + ex.getMessage(), ex);
        }
    
        catch (IOException ioe) {
            Log.e(Tag, "error: " + ioe.getMessage(), ioe);
        }
    }
    
    @Override
    public void run() {
        // TODO Auto-generated method stub
    
    }
    

    }

    【讨论】:

      【解决方案2】:

      调用 AsyncTask 类中的 uploadOrderFile 方法。你会修复它

      对于 AsyncTask 类,请参考此链接 How to execute some code in Android UI thread async?

      【讨论】:

      • 嗨@prakash!它没有帮助。目前我们使用下面的代码来调用我们的uploadOrderFile:
      • 'final ProgressDialog dialog = ProgressDialog.show(this, "","正在上传订单。请稍候!", true);新线程(new Runnable() { public void run() { String error = uploadOrderFile(getBaseContext()); dialog.dismiss(); return; } }).start();'
      猜你喜欢
      • 2014-02-05
      • 2015-07-05
      • 2016-08-07
      • 2012-07-24
      • 2023-04-02
      • 1970-01-01
      • 1970-01-01
      • 2011-05-04
      • 2017-01-03
      相关资源
      最近更新 更多