从安卓设备上传多张图片到PHP服务器

3
这是一段关于在服务器端使用 PHP 的代码的求助。我对 PHP 没有任何了解,但我需要从 Android 上传三张图片到这个 PHP 页面。
我已经尝试了很多方法并进行了搜索,但没有任何教程或其他东西能够帮助我。我的 Android 代码可以正常工作,DNS 也已经配置好了,但图片在服务器端没有显示出来。请帮我提供 Java 代码。
PHP:
<?php
if ($_FILES["file1"]["error"] > 0)
{
    header("HTTP/1.1 400 Bad Request");
    echo "Error: " . $_FILES["file1"]["error"] . "<br />";
}
else if ($_FILES["file2"]["error"] > 0)
{
    header("HTTP/1.1 400 Bad Request");
    echo "Error: " . $_FILES["file1"]["error"] . "<br />";
}
else if ($_FILES["file3"]["error"] > 0)
{
    header("HTTP/1.1 400 Bad Request");
    echo "Error: " . $_FILES["file1"]["error"] . "<br />";
}
else
{
    if ($_FILES["file1"]["error"] > 0)
    {
        echo "Error: " . $_FILES["file1"]["error"] . "<br />";
    }
    else
    {
        echo "Upload: " . $_FILES["file1"]["name"] . "<br />";
        echo "Type: " . $_FILES["file1"]["type"] . "<br />";
        echo "Size: " . ($_FILES["file1"]["size"] / 1024) . " Kb<br />";
        echo "Stored in: " . $_FILES["file1"]["tmp_name"]. "<br />";
    }

    //$target_path = "uploads/";
    $target_path = "elp/pendingimages/";

    $target_path = $target_path . basename( $_FILES['file1']['name']); 

    if(move_uploaded_file($_FILES['file1']['tmp_name'], $target_path)) {
        echo "The file ".  basename( $_FILES['file1']['name']). 
            " has been uploaded"; 
    } 
    else{
        echo "There was an error uploading the file, please try again!";
    }

    if ($_FILES["file2"]["error"] > 0)
    {
        echo "Error: " . $_FILES["file2"]["error"] . "<br />";
    }
    else
    {
        echo "Upload: " . $_FILES["file2"]["name"] . "<br />";
        echo "Type: " . $_FILES["file2"]["type"] . "<br />";
        echo "Size: " . ($_FILES["file2"]["size"] / 1024) . " Kb<br />";
        echo "Stored in: " . $_FILES["file2"]["tmp_name"]. "<br />";
    }

    //$target_path = "uploads/";
    $target_path = "elp/pendingimages/";

    $target_path = $target_path . basename( $_FILES['file2']['name']); 

    if(move_uploaded_file($_FILES['file2']['tmp_name'], $target_path)) {
        echo "The file ".  basename( $_FILES['file2']['name']). 
        " has been uploaded";
    } 
    else{
        echo "There was an error uploading the file, please try again!";
    }

    if ($_FILES["file3"]["error"] > 0)
    {
        echo "Error: " . $_FILES["file3"]["error"] . "<br />";
    }
    else
    {
        echo "Upload: " . $_FILES["file3"]["name"] . "<br />";
        echo "Type: " . $_FILES["file3"]["type"] . "<br />";
        echo "Size: " . ($_FILES["file3"]["size"] / 1024) . " Kb<br />";
        echo "Stored in: " . $_FILES["file3"]["tmp_name"]. "<br />";
    }


    //$target_path = "uploads/";
    $target_path = "elp/pendingimages/";

    $target_path = $target_path . basename( $_FILES['file3']['name']);  

    if(move_uploaded_file($_FILES['file3']['tmp_name'], $target_path)) {
        echo "The file ".  basename( $_FILES['file3']['name']). 
            " has been uploaded";
    } 
    else{
        echo "There was an error uploading the file, please try again!";
    }
}

?>

Java:
public class TryprojectActivity extends Activity {
    InputStream is;
    int pic_count = 0;
    Bitmap bitmap=null;
    FileInputStream in1,in2,in3;
    BufferedInputStream buf;

@Override
public void onCreate(Bundle icicle) {
    super.onCreate(icicle);
    setContentView(R.layout.main);

        try {
            in1 = new FileInputStream("/sdcard/1.jpg");
        } 
        catch (FileNotFoundException e2) {
        // TODO Auto-generated catch block
            e2.printStackTrace();
        }

        try {
            in2 = new FileInputStream("/sdcard/2.jpg");
        } catch (FileNotFoundException e1) {
        // TODO Auto-generated catch block
        e1.printStackTrace();
    } 

    try {
        in3 = new FileInputStream("/sdcard/3.jpg");
    } 
    catch (FileNotFoundException e1) {
        // TODO Auto-generated catch block
        e1.printStackTrace();
    } 

    Bitmap bitmapOrg1 = BitmapFactory.decodeStream(in1);
    ByteArrayOutputStream bao1 = new ByteArrayOutputStream();
    bitmapOrg1.compress(Bitmap.CompressFormat.JPEG, 90, bao1);
    byte [] imagearray1 = bao1.toByteArray();
    String ba1=Base64.encode(imagearray1);

    Bitmap bitmapOrg2 = BitmapFactory.decodeStream(in2);
    ByteArrayOutputStream bao2 = new ByteArrayOutputStream();
    bitmapOrg2.compress(Bitmap.CompressFormat.JPEG, 90, bao2);
    byte [] imagearray2 = bao2.toByteArray();
    String ba2=Base64.encode(imagearray2);

    Bitmap bitmapOrg3 = BitmapFactory.decodeStream(in3);
    ByteArrayOutputStream bao3 = new ByteArrayOutputStream();
    bitmapOrg3.compress(Bitmap.CompressFormat.JPEG, 90, bao3);
    byte [] imagearray3 = bao3.toByteArray();
    String ba3=Base64.encode(imagearray3);

    List<NameValuePair> nameValuePairs = new ArrayList<NameValuePair>(3);

    nameValuePairs.add(new BasicNameValuePair("image1",ba1));
    nameValuePairs.add(new BasicNameValuePair("image2",ba2));
    nameValuePairs.add(new BasicNameValuePair("image3",ba3));

    try{
        HttpClient httpclient = new DefaultHttpClient();
        HttpPost httppost = new HttpPost("http://helpdesk.cispl.com/upload_file.php");
        UrlEncodedFormEntity obj = new UrlEncodedFormEntity(nameValuePairs);
        obj.setChunked(true);
        httppost.setEntity(obj);
        HttpResponse response = httpclient.execute(httppost);
        HttpEntity entity = response.getEntity();
        //is = entity.getContent();
        httpclient.getConnectionManager().shutdown(); 
    }
    catch(Exception e){
        //CommonFunctions.writeLOG(ctx.getClass().toString(), e.toString());
        //CommonFunctions.showToast(ctx, "Unable to post captured image file: " +
        //e.toString());
    }
}

这些图片必须通过HTTP上传,你是如何进行上传的?(因为你提到了Java) - greut
我是指在Android应用程序中所需的Java Activity代码。我已经尝试使用HTTP和Multipart上传,但没有用。这可能是因为我在不了解PHP的情况下尝试编码。 - user1160020
@user1160020,PHP 代码是正确的。所以不要怪你的 PHP 知识。看起来你的多部分请求中有错误。 - Dmitry Zaytsev
我也尝试过使用multipart,但目前我正在使用这段代码,并且代码中没有错误或其他问题。:S - user1160020
@user1160020 你的问题解决了吗?能否请您告诉我解决方案?你提出的代码看起来和我的完全一样。 - Korhan
3个回答

2

看起来你的PHP是正确的。

在你的设备上使用HTTP POST请求和MultipartEntity数据类型。在这里阅读更多信息。

编辑

来自我链接的示例:

您需要下载其他库才能运行MultipartEntity

1)从http://james.apache.org/download.cgi#Apache_Mime4J下载httpcomponents-client-4.1.zip,并将apache-mime4j-0.6.1.jar添加到您的项目中。

2)从http://hc.apache.org/downloads.cgi下载httpcomponents-client-4.1-bin.zip,并将httpclient-4.1.jar、httpcore-4.1.jar和httpmime-4.1.jar添加到您的项目中。

3)使用下面的示例代码。



    private DefaultHttpClient mHttpClient;
public ServerCommunication() { HttpParams params = new BasicHttpParams(); params.setParameter(CoreProtocolPNames.PROTOCOL_VERSION, HttpVersion.HTTP_1_1); mHttpClient = new DefaultHttpClient(params); }
public void uploadUserPhoto(File image1, File image2, File image3) {
try {
HttpPost httppost = new HttpPost("some url");
MultipartEntity multipartEntity = new MultipartEntity(HttpMultipartMode.BROWSER_COMPATIBLE); multipartEntity.addPart("Title", new StringBody("Title")); multipartEntity.addPart("Nick", new StringBody("Nick")); multipartEntity.addPart("Email", new StringBody("Email")); multipartEntity.addPart("Description", new StringBody(Settings.SHARE.TEXT)); multipartEntity.addPart("file1", new FileBody(image1)); multipartEntity.addPart("file2", new FileBody(image2)); multipartEntity.addPart("file3", new FileBody(image3)); httppost.setEntity(multipartEntity);
mHttpClient.execute(httppost, new PhotoUploadResponseHandler());
} catch (Exception e) { Log.e(ServerCommunication.class.getName(), e.getLocalizedMessage(), e); } }
private class PhotoUploadResponseHandler implements ResponseHandler {
@Override public Object handleResponse(HttpResponse response) throws ClientProtocolException, IOException {
HttpEntity r_entity = response.getEntity(); String responseString = EntityUtils.toString(r_entity); Log.d("UPLOAD", responseString);
return null; }
}

我正在将我的三张图片转换为字节数组,然后将其添加到列表中。之后我该怎么做?还是说我走错了路线? - user1160020
in1 = new FileInputStream("/sdcard/1.jpg"); Bitmap bitmapOrg1 = BitmapFactory.decodeStream(in1); ByteArrayOutputStream bao1 = new ByteArrayOutputStream(); bitmapOrg1.compress(Bitmap.CompressFormat.JPEG, 90, bao1); byte [] imagearray1 = bao1.toByteArray(); String ba1=Base64.encode(imagearray1);我对所有三个图像都执行这些操作。 - user1160020
看看我的例子。采用这种方法,MultipartEntity将为您完成一切。您只需要从文件创建FileBody(并从图像创建文件)。 - Dmitry Zaytsev
reqEntity.addpart(); 命令出错,配置路径... 即使我已经提供了 Apache 和 Http Jar 路径。 - user1160020
类型 org.apache.james.mime4j.message.SingleBody 无法解析。它是从所需的 .class 文件中间接引用的。 - user1160020
@DmitryZaitsev能否回答一下我关于类似问题的提问(http://stackoverflow.com/questions/14567050/uploading-multiple-images-to-server)?但我的图像数据是位图。 - Korhan

1

首先,您的代码可以优化为以下内容:

$files = array('file1', 'file2', 'file3');
$path = 'elp/pendingimages/';

foreach ($files as $file) {
    if ($_FILES[$file]['error'] > 0) {
        echo 'Error: '. $_FILES[$file]['error'] .'<br />';
    }
    else {
        echo 'Upload: '. $_FILES[$file]['name'] .'<br />';
        echo 'Type: '. $_FILES[$file]['type'] .'<br />';
        echo 'Size: '. ($_FILES[$file]['size'] / 1024) .' Kb<br />';
        echo 'Stored in: '. $_FILES[$file]['tmp_name'] .'<br />';
    }

    $basename = basename($_FILES[$file]['name']);

    if (move_uploaded_file($_FILES[$file]['tmp_name'], $path . $basename) {
        echo "The file {$basename} has been uploaded";
    }
    else {
        echo 'There was an error uploading the file, please try again!';
    }
}

如果您为每个文件使用不同的字段,则没问题。
接下来,您可以看到当进行多文件上传时,$_FILES数组存储了什么:
$_FILES = array(
    ['files'] => array(
        ['name'] => array(
            [0] => 'WALL_video.jpg'
            [1] => 'WALLc.jpg'
        )
        ['type'] => array(
            [0] => 'image/jpeg'
            [1] => 'image/jpeg'
        )
        ['tmp_name'] => array(
            [0] => '/tmp/phpnbKcdM'
            [1] => '/tmp/phpnrHSN1'
        )
        ['error'] => array(
            [0] => 0
            [1] => 0
        )
        ['size'] => array(
            [0] => 885968
            [1] => 839713
        )
    )
)

如果您正在使用名称为files[]的文件数组字段,则以下代码将适用于您。
$target_path = 'elp/pendingimages/';

foreach ($_FILES['files']['name'] as $index => $name) {
    if ($_FILES['files']['error'][$index] > 0) {
        echo 'Error: ' . $_FILES['files']['error'][$index] . '<br />';
    }
    else {
        echo 'Upload: '. $_FILES['files']['name'][$index] .'<br />';
        echo 'Type: '. $_FILES['files']['type'][$index] .'<br />';
        echo 'Size: '. ($_FILES['files']['size'][$index] / 1024) .' Kb<br />';
        echo 'Stored in: '. $_FILES['files']['tmp_name'][$index] .'<br />';
    }

    $path = $target_path . basename($name);

    if (move_uploaded_file($_FILES['files']['tmp_name'][$index], $path) {
        echo "The file {$name} has been uploaded";
    }
    else {
        echo 'There was an error uploading the file, please try again!';
    }
}

0

请查看我的关于向服务器发送多张图片的帖子 点击这里


网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接