Android:上传文件加上发送带有JSON / PHP的字符串

时间:2013-09-27 06:01:58

标签: php android json

我不是PHP的专家,所以我从互联网和本页的问题中获取了很多东西。我需要将文件发送到WAMP服务器(单独的PHP脚本)并发送一个字符串以创建目标路径,这将取决于日期加上发送的字符串。 目标路径仅基于实际日期。例如2013-09-27,但我想成为2013-09-27-XX,其中XX是设备与上传文件一起发送到服务器的字符串。

以下是我用来将文件上传到服务器的代码。

 public void upload() throws Exception {
        HttpURLConnection connection = null;
        DataOutputStream outputStream = null;

        String pathToOurFile = "/sdcard/"+Ident.getDNI()+"_"+Nombres.getNom()+"_"+Nombres.getApe1()+"_"+Nombres.getApe2()+".xml";
        String urlServer = "http://10.0.0.15/subida/upload_file.php";

        String lineEnd = "\r\n";
        String twoHyphens = "--";
        String boundary = "*****";

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

            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);

            String serverResponseMessage = connection.getResponseMessage();


            fileInputStream.close();
            outputStream.flush();
            outputStream.close();
    }

以下是我用来获取文件的PHP脚本(基于日期):

<?php
mkdir($target_path.date("Y-m-d"));
$target_path = $target_path  .date("Y-m-d") ."/" .basename( $_FILES['uploadedfile']['name']);
if(move_uploaded_file($_FILES['uploadedfile']['tmp_name'], $target_path)) {
 echo "El fichero ".  basename( $_FILES['uploadedfile']['name'])." ha sido enviado";
} else{
 echo "Hubo un error, inténtalo de nuevo!";
}
?>

我假设我应该在这里添加类似$SentString = $_POST('sentstring)的内容,然后将其添加到目标路径:

 $target_path = $target_path  .date("Y-m-d")-$SentString ."/" .basename( $_FILES['uploadedfile']['name']);

但是我应该在Android客户端部分添加什么?

感谢您的时间

1 个答案:

答案 0 :(得分:1)

在查看代码时,这是多部分请求,您可以使用多部分库来上传多部分文件。

下载图书馆

apache-mime4j-0.6.jar
httpclient-4.1.jar
httpcore-4.1.jar
httpmime-4.1.jar

以下几行代码上传代码

try {
                HttpClient httpClient = new DefaultHttpClient();
                httpClient.getParams().setParameter(
                        CoreProtocolPNames.PROTOCOL_VERSION,
                        HttpVersion.HTTP_1_1);
                HttpPost post   = new HttpPost(url);

                post.setHeader("Content-Type", "image/jpg");

                MultipartEntity entity = new MultipartEntity();
                entity.addPart("image",  new FileBody(new File(filePath)));
                post.setEntity(entity);
                try {
                    HttpResponse response = httpClient.execute(post);
                    System.out.println("response -- " + response.getEntity().getContent());

                } catch (IOException e) {
                    e.printStackTrace();  //To change body of catch statement use File | Settings | File Templates.
                }

使用下面的字符串添加字符串数据

entity.addPart("date", new StringBody("date"));