【问题标题】:Upload file and image to php server in android将文件和图像上传到android中的php服务器
【发布时间】:2012-11-18 01:24:12
【问题描述】:

我在java中使用以下代码通过网络将图像上传到php服务器。

import java.io.DataInputStream;
import java.io.DataOutputStream;
import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;
import java.net.HttpURLConnection;
import java.net.MalformedURLException;
import java.net.URL;

import android.util.Log;

public class UploadFiles {

    public void upload(String selectedPath) throws IOException {
        HttpURLConnection conn = null;
        DataOutputStream dos = null;
        DataInputStream inStream = null;
        String lineEnd = "\r\n";
        String twoHyphens = "--";
        String boundary = "AaB03x87yxdkjnxvi7";
        int bytesRead, bytesAvailable, bufferSize;
        byte[] buffer;
        int maxBufferSize = 1 * 1024 * 1024;
        String urlString = "http://android.1mohammadi.ir/nightly/upload_files.php";
        try {
            // ------------------ CLIENT REQUEST
            FileInputStream fileInputStream = new FileInputStream(new File(
                    selectedPath));
            // open a URL connection to the Servlet
            URL url = new URL(urlString);
            // 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("ENCTYPE", "multipart/form-data");
            conn.setRequestProperty("Content-Type",
                    "multipart/form-data;boundary=" + boundary);
            conn.setRequestProperty("uploaded_file", selectedPath);
            dos = new DataOutputStream(conn.getOutputStream());

            dos.writeBytes(twoHyphens + boundary + lineEnd);
            dos.writeBytes("Content-Disposition: form-data; name=\"uploaded_file\";filename=\""
                    + selectedPath + "\"" + lineEnd);
            dos.writeBytes(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 <span id="IL_AD4" class="IL_AD">write</span> 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);
            // close <span id="IL_AD3" class="IL_AD">streams</span>
            Log.e("Debug", "File is written");
            fileInputStream.close();
            dos.flush();
            dos.close();
        } catch (MalformedURLException ex) {
            Log.e("Debug", "error: " + ex.getMessage(), ex);
        } catch (IOException ioe) {
            Log.e("Debug", "error: " + ioe.getMessage(), ioe);
        }
        // ------------------ read the SERVER RESPONSE
        try {
            inStream = new DataInputStream(conn.getInputStream());
            String str;

            while ((str = inStream.readLine()) != null) {
                Log.e("Debug", "Server Response " + str);
            }
            inStream.close();

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

在 php 服务器中使用这个:

<?php
// Where the file is going to be placed
$target_path = "/uploads/";

/* Add the original filename to our target path.
Result is "uploads/filename.<span id="IL_AD5" class="IL_AD">extension</span>" */
$target_path = $target_path . basename($_FILES['uploadedfile']['name']);

error_log("Upload File >>" . $target_path . "\r\n", 3, "Log.log");

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!";
    echo "filename: " . basename($_FILES['uploadedfile']['name']);
    echo "target_path: " . $target_path;
}
?>

在 android 代码中不会发生任何错误,在 php 代码中也是如此。当文件上传无法移动文件时。我该如何解决这个问题? 谢谢。

【问题讨论】:

  • 你检查过php端的上传是否成功了吗? $_FILES 中的['error'] 参数应该始终被选中。
  • @MarcB 我使用error_log("Upload File &gt;&gt;" .basename($_FILES['uploadedfile']['name']) . " \r\n", 3, "Log.log");,输出为:Upload File &gt;&gt;uploads/ Upload File &gt;&gt;
  • 这意味着没有提供文件名。 ['name'] 为空白。
  • 我使用来自reecon.wordpress.com/2010/04/25/…的代码并解决了问题

标签: php android file-upload


【解决方案1】:
private void postFile() {
    try {

        // Url to upload file to. Mine points to my folder in xampp
        String postReceiverUrl = "http://ipv4_address/webinterface/UploadToServer.php";
        Log.v("Some message", "postURL: " + postReceiverUrl);

        // new HttpClient
        HttpClient httpClient = new DefaultHttpClient();

        // post header
        HttpPost httpPost = new HttpPost(postReceiverUrl);

        // Gets the image from my drawable folder and compresses it
        Bitmap bm = BitmapFactory.decodeResource(getResources(),
                R.drawable.goku);
        File file = new File(getExternalCacheDir().toString(), "goku.jpg");
        FileOutputStream outStream = new FileOutputStream(file);
        bm.compress(Bitmap.CompressFormat.JPEG, 100, outStream);
        outStream.flush();
        outStream.close();

        // Uri.fromFile(file);

        // File file = new
        // File(Environment.getExternalStorageDirectory(),"goku.jpg");
        // file.getAbsolutePath();
        FileBody fileBody = new FileBody(file);

        MultipartEntity reqEntity = new MultipartEntity(
                HttpMultipartMode.BROWSER_COMPATIBLE);
        reqEntity.addPart("file", fileBody);
        httpPost.setEntity(reqEntity);

        // execute HTTP post request
        HttpResponse response = httpClient.execute(httpPost);
        HttpEntity resEntity = response.getEntity();

        if (resEntity != null) {

            String responseStr = EntityUtils.toString(resEntity).trim();
            Log.v("Some message", "Response: " + responseStr);
        }

    } catch (NullPointerException e) {
        e.printStackTrace();
    } catch (Exception e) {
        e.printStackTrace();
    }
}

【讨论】:

  • 这是我的 php 文件
【解决方案2】:

1mohammadi.ir 回答得很好。我只是想在他的代码上添加一些东西。

要调用上传函数,你需要在另一个线程(不是主线程)中调用。 通过这样做,请点击此链接。 How to fix android.os.NetworkOnMainThreadException?

【讨论】:

    【解决方案3】:

    我在服务器中使用此代码:

    <?php
    $target_path = "./uploads/";
    $target_path = $target_path . basename($_FILES['uploadedfile']['name']);
    
    error_log("Upload File >>" . $target_path . $_FILES['error'] . " \r\n", 3,
        "Log.log");
    
    error_log("Upload File >>" . basename($_FILES['uploadedfile']['name']) . " \r\n",
        3, "Log.log");
    
    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!";
    }
    ?>
    

    并在 android 中使用此代码:

    package ir.mohammadi.android.nightly.tools;
    
    import java.io.DataInputStream;
    import java.io.DataOutputStream;
    import java.io.File;
    import java.io.FileInputStream;
    import java.io.IOException;
    import java.net.HttpURLConnection;
    import java.net.URL;
    
    public class UploadFiles {
    
        public void upload(String selectedPath) throws IOException {
    
            HttpURLConnection connection = null;
            DataOutputStream outputStream = null;
            DataInputStream inputStream = null;
    
            String pathToOurFile = selectedPath;
            String urlServer = "http://android.1mohammadi.ir/nightly/upload_files.php";
            String lineEnd = "\r\n";
            String twoHyphens = "--";
            String boundary = "*****";
    
            int bytesRead, bytesAvailable, bufferSize;
            byte[] buffer;
            int maxBufferSize = 1 * 1024 * 1024;
    
            try {
                FileInputStream fileInputStream = new FileInputStream(new File(
                        pathToOurFile));
    
                URL url = new URL(urlServer);
                connection = (HttpURLConnection) url.openConnection();
    
                connection.setDoInput(true);
                connection.setDoOutput(true);
                connection.setUseCaches(false);
    
                connection.setRequestMethod("POST");
    
                connection.setRequestProperty("Connection", "Keep-Alive");
                connection.setRequestProperty("Content-Type",
                        "multipart/form-data;boundary=" + boundary);
    
                outputStream = new DataOutputStream(connection.getOutputStream());
                outputStream.writeBytes(twoHyphens + boundary + lineEnd);
                outputStream
                        .writeBytes("Content-Disposition: form-data; name=\"uploadedfile\";filename=\""
                                + pathToOurFile + "\"" + lineEnd);
                outputStream.writeBytes(lineEnd);
    
                bytesAvailable = fileInputStream.available();
                bufferSize = Math.min(bytesAvailable, maxBufferSize);
                buffer = new byte[bufferSize];
    
                bytesRead = fileInputStream.read(buffer, 0, bufferSize);
    
                while (bytesRead > 0) {
                    outputStream.write(buffer, 0, bufferSize);
                    bytesAvailable = fileInputStream.available();
                    bufferSize = Math.min(bytesAvailable, maxBufferSize);
                    bytesRead = fileInputStream.read(buffer, 0, bufferSize);
                }
    
                outputStream.writeBytes(lineEnd);
                outputStream.writeBytes(twoHyphens + boundary + twoHyphens
                        + lineEnd);
    
                int serverResponseCode = connection.getResponseCode();
                String serverResponseMessage = connection.getResponseMessage();
    
                fileInputStream.close();
                outputStream.flush();
                outputStream.close();
            } catch (Exception ex) {
            }
        }
    }
    

    欲了解更多信息,请转至link

    【讨论】:

    • 在这里面,它会从哪里拍照?
    • @RajBedi selectedPath 是图片地址
    【解决方案4】:

    这可能是写入上传目录的问题。确保/uploads/ 目录存在并且可以被网络服务器写入。

    您也可以use curl 来测试您的服务器代码。一旦成功,您就可以继续让客户端工作。

    【讨论】:

    • 上传目录已存在。
    猜你喜欢
    • 2016-03-29
    • 1970-01-01
    • 2011-02-02
    • 2015-03-29
    • 2011-10-15
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多