将参数传递给多部分表单

时间:2015-07-07 14:12:38

标签: php android multipartform-data

我想在上传图片时传递参数。但是图像上传但我无法获取参数。实际上,参数或图像都可以上传,但不能同时上传。此外,参数不作为字符串接收,而是作为������JFIF������H��H��������XExif����MM��* received 。 我需要帮助。我找了类似的问题,但找不到答案。

        _conn = (HttpURLConnection)_url.openConnection();
        _conn.setDoOutput(true);
        _conn.setDoInput(true);
        _conn.setUseCaches(false);
        _conn.setRequestProperty("Connection", "Keep-Alive");
        _conn.setRequestProperty("Content-Type", "multipart/form-data;boundary=" + boundary);
        dos = new DataOutputStream(_conn.getOutputStream());

        dos.writeBytes(twoHyphens + boundary + lineEnd);
        String id = "h";
        dos.writeBytes("Content-Disposition: form-data; name=\"id\"" + lineEnd);
        dos.writeBytes("content-type: text/plain");
        dos.writeBytes(id);
        dos.writeBytes(lineEnd);

       dos.writeBytes(twoHyphens + boundary + lineEnd);

        dos.writeBytes("Content-Disposition: form-data; name=\"photo\";filename=\"" + path + "\"" + lineEnd);
        dos.writeBytes(lineEnd);

        bytesAvailable = fileInputStream.available();
        bufferSize = Math.min(bytesAvailable, maxBufferSize);
        buffer = new byte[bufferSize];

        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);
        }
        dos.writeBytes(lineEnd);
        dos.writeBytes(twoHyphens + boundary + twoHyphens + lineEnd);

        dos.flush();
        dos.close();

        fileInputStream.close();

        BufferedReader reader = new BufferedReader(new InputStreamReader(_conn.getInputStream()));
        String temp_string;
        StringBuilder mystring = new StringBuilder();
        while((temp_string = reader.readLine()) != null)
        {
            mystring.append(temp_string);
        }

        Log.v(LOG_TAG, mystring.toString());
        return mystring.toString();

    } 

这是php代码

     if($_SERVER["REQUEST_METHOD"] == "POST")
    {

       $id = $_POST['id'];
    echo "id ". (string)$id;

      if(isset($_FILES["photo"]["name"])){

      $temp = explode(".",$_FILES["photo"]["name"]);

      $target_file = $target_dir . $id. "." . end($temp);

        echo $target_file;

     if(move_uploaded_file($_FILES["photo"]["tmp_name"], $target_file))
      {
    echo "success";
       }
     else
       {
        echo( "error".$con->error);
       }

1 个答案:

答案 0 :(得分:-1)

我碰巧做了类似的事情。我在这里发布我的代码。我希望您能够根据需要进行编辑。在这里,我上传图像并传递json对象。 如果您仍然面临这个问题,请告诉我。这段代码对我来说非常合适。

 String attachmentName = "bitmap";
        String attachmentFileName = "bitmap.bmp";
        String crlf = "\r\n";
        String twoHyphens = "--";
        String boundary = "*****";

        @Override
        protected void onPreExecute() {
            super.onPreExecute();
            // Shows Progress Bar Dialog and then call doInBackground method
            // showDialog(progress_bar_type);


            progDailog.setMessage("Please Wait!");
            progDailog.setIndeterminate(false);
            progDailog.setProgressStyle(ProgressDialog.STYLE_SPINNER);
            progDailog.setCancelable(true);
            progDailog.show();

        }


        protected Boolean doInBackground(String... urls) {



                Log.d("inbakcground", "cheked");
                Log.d("str ", PublishActivity.recipeStr[0]);


            try {

                ImageButton coverImage = (ImageButton) findViewById(R.id.CoverPic);
                JSONObject recipeJson = new JSONObject();
                recipeJson.put("Title", PublishActivity.recipeStr[0]);
                recipeJson.put("Ingredients", PublishActivity.recipeStr[1]);
                recipeJson.put("Recipe", PublishActivity.recipeStr[2]);
                recipeJson.put("Author", PublishActivity.recipeStr[3]);
                URL urlImage = new URL("http://10.0.2.2:8080/websevice");
                HttpURLConnection urlConnectionImage = (HttpURLConnection) urlImage.openConnection();
                Bitmap bitmap = ((BitmapDrawable) coverImage.getDrawable()).getBitmap();
                urlConnectionImage.setUseCaches(false);
                urlConnectionImage.setDoOutput(true);
                urlConnectionImage.setDoInput(true);
                urlConnectionImage.setRequestMethod("POST");
                urlConnectionImage.setRequestProperty("Connection", "Keep-Alive");
                urlConnectionImage.setRequestProperty("Cache-Control", "no-cache");
                urlConnectionImage.setRequestProperty("Content-Type", "multipart/form-data;boundary=" + this.boundary);
                DataOutputStream request = new DataOutputStream(urlConnectionImage.getOutputStream());
                request.writeBytes(this.twoHyphens + this.boundary + this.crlf);
                request.writeBytes("Content-Disposition: form-data; name=\"" + this.attachmentName + "\";filename=\"" + this.attachmentFileName + "\"" + this.crlf);
                request.writeBytes(this.crlf);
              /*  byte[] pixels = new byte[bitmap.getWidth() * bitmap.getHeight()];
                for (int i = 0; i < bitmap.getWidth(); ++i) {
                    for (int j = 0; j < bitmap.getHeight(); ++j) {
                        //we're interested only in the MSB of the first byte,
                        //since the other 3 bytes are identical for B&W images
                        pixels[i + j] = (byte) ((bitmap.getPixel(i, j) & 0x80) >> 7);
                    }
                }*/
                ByteArrayOutputStream bos = new ByteArrayOutputStream();
                bitmap.compress(Bitmap.CompressFormat.PNG, 0 /*ignored for PNG*/, bos);
                byte[] bitmapdata = bos.toByteArray();
                request.write(bitmapdata);
                request.writeBytes(this.crlf);
             //   request.writeBytes(this.twoHyphens + this.boundary + this.twoHyphens + this.crlf);
                request.writeBytes(this.twoHyphens + this.boundary + this.crlf);
                /******json***********/
               String name = "recipe";
               // request.writeBytes(this.twoHyphens + this.boundary + this.crlf);
                request.writeBytes("Content-Disposition: form-data; name=\"" + name + "\";"+ this.crlf);
                request.writeBytes(this.crlf);
                request.writeBytes(recipeJson.toString());
                request.writeBytes(this.crlf);
                request.writeBytes(this.twoHyphens + this.boundary + this.twoHyphens + this.crlf);

                request.flush();
                Log.d("imageout", Integer.toString(urlConnectionImage.getResponseCode()));
                request.close();



            } catch (Exception e) {
                Log.d("exeJsonPublish", e.toString());
                return false;
            }
              return false;
        }


        @Override
        protected void onPostExecute(Boolean result) {
            super.onPostExecute(result);
            progDailog.dismiss();
            if (result) {
                Log.d("hello1 in else", "else");

                Toast.makeText(getApplicationContext(), "Successful", Toast.LENGTH_LONG).show();

                Intent homeI = new Intent(getApplicationContext(), MainActivity.class);
                homeI.putExtra("fromPublish", true);
                homeI.putExtra("position", 0);
                setResult(RESULT_OK, homeI);
                finish();

            } else
                Toast.makeText(getApplicationContext(), "Failed", Toast.LENGTH_LONG).show();
            Log.d("hello in else", "else");


        }
相关问题