在HttpUrlConnection中发送数据和图像

时间:2014-07-30 05:07:53

标签: php android httpurlconnection

我知道这个网站已被问过几次,但我找不到正确的方法。

我想使用HTTPURLCONNECTIONPHP将文件从android上传到服务器。

我找到了一个教程,但只发送文件而不是数据,数据包括文件名,详细信息/说明和评论。

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("uploaded_file", fileName);
conn.setRequestProperty("Filename","testfilename");

JSONObject cred = new JSONObject();
cred.put("name","juan");
cred.put("password","pass");

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

// for every param
dos.writeBytes("Content-Disposition: form-data; name=\"chunk\"" + lineEnd);
dos.writeBytes("Content-Type: text/plain; charset=UTF-8" + lineEnd);
dos.writeBytes("Content-Length: " + cred.length() + lineEnd);
dos.writeBytes(lineEnd);
dos.writeBytes(cred.toString() + lineEnd);
dos.writeBytes(twoHyphens + boundary + lineEnd);

/**Create file*/
dos.writeBytes(twoHyphens + boundary + lineEnd);
dos.writeBytes (cred.toString());
dos.writeBytes("Content-Disposition: form-data; name=\"uploaded_file\";filename=\""+ fileName + "\"" + lineEnd);
dos.writeBytes(lineEnd); //close the streams //
fileInputStream.close();
dos.flush();
dos.close();

PHP:

$name = $this->input->post('name');

$headers = $this->input->request_headers();
// print_r('sample result: - '.$headers['Filename']);
$file_name = $headers['Filename'];
$config2['upload_path'] = 'cms/uploads/reports_images/';
$config2['allowed_types'] = 'jpg|png|xls';
$config2['max_size'] = '2048';
$config2['file_name'] = $file_name.'_'.date('Y_m_d_H_i_s',time());
$this->load->library('upload',$config2);
$this->upload->initialize($config2);

echo "name ".'-'.$name;  
// $file_path = $file_path . basename( $_FILES['uploaded_file']['file_name']);
if($this->upload->do_upload('uploaded_file')) {
    echo "success".'-'.$name;
} else{
    echo "fail";
    print_r($this->upload->display_errors());
}

试图在log cat中打印响应,这就是我得到的:

  

HTTP响应是:name -fail 您没有选择要上传的文件。

我该怎样做才能正确完成?

感谢您的帮助。

4 个答案:

答案 0 :(得分:0)

我使用php在服务器上发送带有其他信息的图像文件。代码如下。这是在server.i上传文件的非常简单的方法。我已经使用了multypartentity。

// ************** Report Crime ******************
public String reportCrime(String uploadFile, int userid, int crimetype,
        String crimedetails, String lat, String longi, String reporteddate,
        Integer language) {
    String url;
    MultipartEntity entity;
    try {
        url = String.format(Constant.SERVER_URL
                + "push_notification/reportCrime.php"); // url of your webservice

        entity = new MultipartEntity(HttpMultipartMode.BROWSER_COMPATIBLE);
        //uploadfile is a path of the image.
        File file = new File(uploadFile);
        if (!file.equals("Image not Provided.")) {
            if (file.exists()) {

                Bitmap bmp = BitmapFactory.decodeFile(uploadFile);
                ByteArrayOutputStream bos = new ByteArrayOutputStream();
                bmp.compress(CompressFormat.JPEG, 70, bos);
                InputStream in = new ByteArrayInputStream(bos.toByteArray());
                ContentBody foto = new InputStreamBody(in, "image/jpeg",
                        uploadFile);

                // FileBody image = new FileBody(file, "image/jpeg");
                entity.addPart("Image", foto);
            }
        } else {
            FormBodyPart image = new FormBodyPart("Image", new StringBody(
                    ""));
            entity.addPart(image);
        }

        FormBodyPart userId = new FormBodyPart("userId", new StringBody(
                String.valueOf(userid)));
        entity.addPart(userId);

        FormBodyPart crimeType = new FormBodyPart("crimetype",
                new StringBody(String.valueOf(crimetype)));
        entity.addPart(crimeType);
        FormBodyPart lanaguagetype = new FormBodyPart("InputLang",
                new StringBody(String.valueOf(language.toString())));
        entity.addPart(lanaguagetype);
        FormBodyPart crimeDetails = new FormBodyPart("crimedetail",
                new StringBody(crimedetails));
        entity.addPart(crimeDetails);

        FormBodyPart latittude = new FormBodyPart("latittude",
                new StringBody(lat));
        entity.addPart(latittude);

        FormBodyPart longitude = new FormBodyPart("longitude",
                new StringBody(longi));
        entity.addPart(longitude);

        FormBodyPart reportedDate = new FormBodyPart("reporteddatetime",
                new StringBody(reporteddate));
        entity.addPart(reportedDate);

    } catch (UnsupportedEncodingException e1) {
        e1.printStackTrace();
        return "error";
    }

    HttpParams httpParams = new BasicHttpParams();

    HttpContext httpContext = new BasicHttpContext();
    HttpConnectionParams.setConnectionTimeout(httpParams, 10000);
    HttpConnectionParams.setSoTimeout(httpParams, 10000);

    try {
        HttpPost httpPost = new HttpPost(url);
        httpPost.setEntity(entity);
        client = new DefaultHttpClient();
        HttpResponse response = client.execute(httpPost);
        BufferedReader in = null;
        try {
            in = new BufferedReader(new InputStreamReader(response
                    .getEntity().getContent()));
            StringBuffer sb = new StringBuffer();
            String line = null;
            String NL = System.getProperty("line.separator");
            while ((line = in.readLine()) != null) {
                sb.append(line + NL);
            }

            result = sb.toString();
        } finally {
            if (in != null)
                in.close();
        }

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

    return result;
}

在php端处理图像文件。

$u_id = $_REQUEST['userId'];
$c_type = $_REQUEST['crimetype'];
$c_detail = $_REQUEST['crimedetail'];
$lat = $_REQUEST['latittude'];
$long = $_REQUEST['longitude'];
$Language= $_REQUEST['InputLang'];
$image = '';
$r_time = $_REQUEST['reporteddatetime'];
$address='';
if (!empty($_FILES["Image"]["tmp_name"])) {     
    $tmp_img = $_FILES["Image"]["tmp_name"];
    $path = $_FILES["Image"]['name'];
    $ext = pathinfo($path, PATHINFO_EXTENSION);
    $imagename = date("YmdHis");
    $image = "http://" . $_SERVER['HTTP_HOST'] . "/webservices/crime-image/" . $imagename . "." . $ext;
    $dirpath = $_SERVER['DOCUMENT_ROOT'] . "/webservices/crime-image/" . $imagename . "." . $ext;
    move_uploaded_file($tmp_img, $dirpath);
}
$query = mysql_query("SELECT crimeId,((ACOS(SIN($lat * PI() / 180) * SIN(`lattitude` * PI() / 180) + COS($lat * PI() / 180) * COS(`lattitude` * PI() / 180) * COS(($long-`Longitude`) * PI() / 180)) * 180 / PI()) * 60 * 1.1515) AS `distance`  FROM crimes where crimeTypeId = '$c_type' and reportedDateTime between ('" . $r_time . " 00:00:00') and ('" . $r_time . "  23:59:59') HAVING `distance`<= '2'");
if (mysql_num_rows($query) > 1) {
    echo 'This Crime Already Register';
} else {
    $query_str = "INSERT INTO  `crimes` (
                            `crimeId` ,
                            `crimeTypeId` ,
                            `crimeDetail` ,
                            `lattitude` ,
                            `longitude` ,
                            `Image` ,
                            `status` ,
                            `reportedDateTime` ,
                            `createdDateTime` ,                               
                            `modifiedDateTime`,
                            `reported_by`,
                            `isDeleted`,
                            `address`
                           )
                           VALUES (
                                    NULL , 
                                    '$c_type', 
                                   '$c_detail',                                                                              
                                   '$lat',
                                   '$long',
                                   '$image',
                                   '0',
                                   '$r_time',
                                   now(),
                                   now(),
                                   '$u_id',
                                   '0',
                                   '$address'

                           )";

    $query = mysql_query($query_str) or die(mysql_error());

答案 1 :(得分:0)

尝试使用HttpRequest库。这减少了很多代码,并且是单个类库。只需将HttpRequest.java复制到您的项目中即可。这是您使用某些数据上传图片的方式。

HttpRequest request = HttpRequest.post("http://google.com");
request.part("status[body]", "Making a multipart request");//this is data
request.part("status[image]", new File("/home/kevin/Pictures/ide.png"));//this is your image
if (request.ok())
  System.out.println("Upload success");

答案 2 :(得分:0)

你肯定已经找到了解决方案,我给出了答案,问题来自php文件。这是我用来从android下载图片到php:

if(isset($_FILES['uploadedfile']))
{ 
    $ok = fwrite($ouverture, 'isset ok'.PHP_EOL);
    $dossier = 'profilesPictures/';
    $ok = fwrite($ouverture, $_FILES['uploadedfile']['name'].PHP_EOL);
    $ok = fwrite($ouverture, $_FILES['uploadedfile']['tmp_name'].PHP_EOL);
    $fichier = basename($_FILES['uploadedfile']['name']);
    if(move_uploaded_file($_FILES['uploadedfile']['tmp_name'], $dossier . $fichier)) 
     {
          // OK
     }
     else 
     {
          // NOK
     }
}

nametmp_name字段已修复,因此您无法使用其他

答案 3 :(得分:0)

您没有使用fileInputStream。

添加 -

dos.write([bytearray from file]);
dos.writeBytes(crlf);
dos.writeBytes(twoHyphens + boundary + twoHyphens + lineEnd);