简体   繁体   English

将参数传递给多部分形式

[英]pass a parameter to multi-part form

I want to pass a parameter with the image being upload. 我想在上传图片时传递参数。 However the image gets uploaded but I am unable to get the parameter. 但是图像被上传,但是我无法获取参数。 In fact, either the parameter or the image gets uploaded but not both. 实际上,参数或图像都会上载,但不会两者都上载。 Also, the parameter is not received as string but as ?JFIF H H XExif MM * . 此外,该参数不会作为字符串接收,而是作为 ?JFIF H H XExif MMMM* 。 I need help. 我需要帮助。 I have looked for similar question but couldnt find answers. 我一直在寻找类似的问题,但找不到答案。

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

    } 

This is the php code 这是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);
       }

I happened to be doing something similar. 我碰巧在做类似的事情。 I am posting my code here. 我在这里发布我的代码。 I hope that you will be able to edit it according to your need. 希望您能够根据需要进行编辑。 Here I am uploading image and passing json object with it. 在这里,我正在上传图像并通过它传递json对象。 Let me know if you still facing the problem.This code is working perfectly for me. 如果您仍然遇到问题,请告诉我。这段代码对我来说非常有效。

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


        }

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM