php - Android 图片上传到服务器,HTTP 响应为 200,但文件未上传

标签 php android eclipse http xampp

这是我服务器上的 php 脚本。

<?php
$target_path1 = "/Pictures/"
$target_path1 = $target_path1 . basename( $_FILES['uploaded_file']['name']);
if(move_uploaded_file($_FILES['uploaded_file']['tmp_name'], $target_path1)) { 
    echo "Success";
} else {
    echo "fail";
}
?>

这是我的 Android Java 代码:

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

import android.content.Context;
import android.util.Log;
import android.widget.Toast;

public class ImageUpload {
private int serverResponseCode = 0;
private String upLoadServerUri = "http://10.0.2.2/Pictures/UploadToServer.php";
private String imagepath = null;
Context context;

public ImageUpload(Context mcontext) {
    context = mcontext;
}

public int uploadFile(String sourceFileUri) {

    String fileName = sourceFileUri;

    HttpURLConnection conn = null;
    DataOutputStream dos = null;
    String lineEnd = "\r\n";
    String twoHyphens = "--";
    String boundary = "*****";
    int bytesRead, bytesAvailable, bufferSize;
    byte[] buffer;
    int maxBufferSize = 1 * 1024 * 1024;
    File sourceFile = new File(sourceFileUri);

    if (!sourceFile.isFile()) {

        // dialog.dismiss();

        Log.e("uploadFile", "Source File not exist :" + imagepath);

        return 0;

    } else {
        try {

            // open a URL connection to the Servlet
            FileInputStream fileInputStream = new FileInputStream(
                    sourceFile);
            URL url = new URL(upLoadServerUri);

            // Open a HTTP connection to the URL
            conn = (HttpURLConnection) url.openConnection();
            conn.setDoInput(true); // Allow Inputs
            conn.setDoOutput(true); // Allow Outputs
            conn.setUseCaches(false); // Don't use a Cached Copy
            conn.setRequestMethod("POST");
            conn.setRequestProperty("Connection", "Keep-Alive");
            conn.setRequestProperty("ENCTYPE", "multipart/form-data");
            conn.setRequestProperty("Content-Type",
                    "multipart/form-data;boundary=" + boundary);
            Toast.makeText(context, fileName, Toast.LENGTH_LONG).show();
            conn.setRequestProperty("uploaded_file", /*fileName*/"test.jpg");

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

            dos.writeBytes(twoHyphens + boundary + lineEnd);
            dos.writeBytes("Content-Disposition: form-data; name=\"uploaded_file\";filename=\""
                    + fileName + "\"" + 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);
                dos.write(buffer, 0, bytesRead);
                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);

            // Responses from the server (code and message)
            serverResponseCode = conn.getResponseCode();
            String serverResponseMessage = conn.getResponseMessage();

            Log.i("uploadFile", "HTTP Response is : "
                    + serverResponseMessage + ": " + serverResponseCode);

            if (serverResponseCode == 200) {

                Toast.makeText(
                        context,
                        "Image Successfully Shuffled and Sent \n You will be notified once it is solved",
                        Toast.LENGTH_SHORT).show();
            }

            // close the streams //
            fileInputStream.close();
            dos.flush();
            dos.close();

        } catch (MalformedURLException ex) {

            ex.printStackTrace();

            Toast.makeText(context, "MalformedURLException",
                    Toast.LENGTH_SHORT).show();

            Log.e("Upload file to server", "error: " + ex.getMessage(), ex);
        } catch (Exception e) {

            e.printStackTrace();

            Toast.makeText(context, "Got Exception : see logcat ",
                    Toast.LENGTH_SHORT).show();
            Log.e("Upload file to server Exception",
                    "Exception : " + e.getMessage(), e);
        }

        return serverResponseCode;

    }
}

}

我正在传递要从我的应用程序上传的 sourceUri,类似于/sdcard/pictures/temp.jpg

请帮助我,响应是 HTTP 响应 200,但服务器上不存在文件。

使用 XAMP phpmyadmin。

最佳答案

Java:

public int uploadFile(String sourceFileUri) {

    HttpURLConnection conn = null;
    DataOutputStream dos = null;
    String lineEnd = "\r\n";
    String twoHyphens = "--";
    String boundary = "*****";
    int bytesRead, bytesAvailable, bufferSize;
    byte[] buffer;
    int maxBufferSize = 1 * 1024 * 1024;
    File sourceFile = new File(sourceFileUri);

    if (!sourceFile.isFile()) {
        Log.e("uploadFile", "Source File not exist :" + uploadFilePath + "" + uploadFileName);
        return 0;
    }
    else
    {
        try {
            // open a URL connection to the Servlet
            FileInputStream fileInputStream = new FileInputStream(sourceFile);
            URL url = new URL(upLoadServerUri);

            // Open a HTTP  connection to  the URL
            conn = (HttpURLConnection) url.openConnection();
            conn.setDoInput(true); // Allow Inputs
            conn.setDoOutput(true); // Allow Outputs
            conn.setUseCaches(false); // Don't use a Cached Copy
            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("uploadedfile", sourceFileUri);

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

            dos.writeBytes(twoHyphens + boundary + lineEnd);
            dos.writeBytes("Content-Disposition: form-data; name=\"uploadedfile\";filename=\"" + sourceFileUri + "\"" + 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);

            // Responses from the server (code and message)
            serverResponseCode = conn.getResponseCode();
            String serverResponseMessage = conn.getResponseMessage();

            Log.i("uploadFile", "HTTP Response is : "+ serverResponseMessage + ": " + serverResponseCode);

            if(serverResponseCode == 200){
                Log.e("uploadFile", "File Uploaded.");
                // Congrats!
            }

            //close the streams //
            fileInputStream.close();
            dos.flush();
            dos.close();

        } catch (Exception e) {
            Log.e("Upload file to server Exception", "Exception : " + e.getMessage(), e);
        }
        return serverResponseCode;

    } // End else block
}

PHP:

<?php
$target_path = "./uploads/";
$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!";
}
?>

它有效!

关于php - Android 图片上传到服务器,HTTP 响应为 200,但文件未上传,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/22533159/

相关文章:

java - 如何在Eclipse中查看maven项目的web内容

php - 是否可以使用 Azure 通信仅使用 REST 端点发送 SMS?

php - 如何从 html/php 页面内的 mySQL 数据库打印表格

php - OOP应用架构: Which layer does a lazy loader sit in?

android - 如何保护我的 SQLite 数据库

Android位图对比实现

android - 在 android eclipse 中找不到与 com.android.support :appcompat-v7:+. 匹配的任何版本

php file_get_contents 执行两次

android - Android 谷歌地图中未启用位置按钮

java - 为什么在 PageParameters 类型上使用 containsKey() 和 getString() 时出现错误?