如何将多个图像上传到PHP服务器?

时间:2019-09-24 15:31:34

标签: android image image-uploading

我有一种方法,可以使用从Android发送到PHP服务器的每个命令发送文本图像。在PHP Server中,我可以通过Web表单向服务器发送多个图像。

如何通过选择图库中的图像并使用单个上载命令将其发送到服务器来将多个图像从Android上载到服务器?也就是说,如何使这种Android方法将多个图像发送到PHP中的代码?

我用于通过Android上传图像的方法如下:

private String uploadFile() {
    String responseString = null;
    HttpClient httpclient = new DefaultHttpClient();
    HttpPost httppost = null;
    File sourceFile = null;

    try {
        sourceFile = new File(imageStoragePath);
    } catch (Exception e) {
        e.printStackTrace();
    }
    httppost = new HttpPost(ConfigEnderecosURL.URL_ImagemEnviaImagem);

    try {
        ImagemCameraEnviaImagemMultiPart entity = new ImagemCameraEnviaImagemMultiPart(
                new ImagemCameraEnviaImagemMultiPart.ProgressListener() {
                    @RequiresApi(api = Build.VERSION_CODES.CUPCAKE)
                    @Override
                    public void transferred(long num) {
                        publishProgress((int) ((num / (float) totalSize) * 100));
                    }
                });
        try {
            String comentario = edComentario.getText().toString();

            // Adding file data to http body
            entity.addPart("image", new FileBody(sourceFile));
            entity.addPart("usuario_id", new StringBody(idUsuario));
            entity.addPart("profissao", new StringBody(profissao, Charset.forName(HTTP.UTF_8)));
            entity.addPart("profissao_id", new StringBody(idProfissao));
            entity.addPart("comentario", new StringBody(comentario, Charset.forName(HTTP.UTF_8)));

        } catch (Exception e) {
            e.printStackTrace();
        }
        totalSize = entity.getContentLength();
        httppost.setEntity(entity);

        // Making server call
        HttpResponse response = httpclient.execute(httppost);
        HttpEntity r_entity = response.getEntity();
        int statusCode = response.getStatusLine().getStatusCode();

        if (statusCode == 200) {
            // Server response
            responseString = EntityUtils.toString(r_entity);
        } else {
            responseString = "erro";
        }
        return responseString;
    } catch (ClientProtocolException e) {
        responseString = "erro";
        e.printStackTrace();
    } catch (Exception e) {
        responseString = "erro";
        e.printStackTrace();
    }
    return responseString;
}

在PHP中,有一个类可以接收通过Web表单上传的多个文件。

$diretorio = "imagens/";

$arquivo = isset ( $_FILES ['arquivo'] ) ? $_FILES ['arquivo'] : FALSE;

for($controle = 0; $controle < count ( $arquivo ['name'] ); $controle ++) {
    $destino = $diretorio . "/" . $arquivo ['name'] [$controle];
    if (move_uploaded_file ( $arquivo ['tmp_name'] [$controle], $destino )) {
        echo "Upload realizado com sucesso.<br>";
    } else {
        echo "Erro ao realizar upload";
    }
}

0 个答案:

没有答案