上传图片JPEG格式的多部分文件在android的服务器 [英] Upload image in jpeg format in multipart file on server in android

查看:130
本文介绍了上传图片JPEG格式的多部分文件在android的服务器的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

您好,我正在开发一个需要发布的JPEG格式图像的一些在多部分文件格式的服务器应用程序,我已经写了如下$ C $下这一点,但它给下面的响应,

  01-15 00:32:14.119:我/的System.out(7598):文件上传{地位:错误,消息:请,指定有效的参数文件}
 

请帮助我的人。提前致谢 。 这是我的活动code

 公共类SendPostActivity扩展活动实现OnClickListener {
    私人语境appContext;
    私人字符串为messageType;
    HashMap的<字符串,字符串>的fileList =新的HashMap<字符串,字符串>();
    公共字符串finalImagePath = NULL;
    //图像的数量来选择
    私有静态最终诠释PICK_IMAGE = 1;

    @覆盖
    保护无效的onCreate(包savedInstanceState){
        // TODO自动生成方法存根
        super.onCreate(savedInstanceState);
        overridePendingTransition(R.anim.slide_in_left,R.anim.slide_out_right);
        的setContentView(R.layout.activity_send_post);
        overridePendingTransition(R.anim.slide_in_right,R.anim.slide_out_left);

        appContext =这一点;
        initComponent();
    }

    私人无效initComponent(){

        ((按钮)findViewById(R.id.btnLeftNav))setVisibility(View.VISIBLE)。
        ((按钮)findViewById(R.id.btnRightNav))setVisibility(View.VISIBLE)。
        ((按钮)findViewById(R.id.btnRightNav))
                .setBackgroundResource(R.drawable.send_btn);
        ((按钮)findViewById(R.id.btnLeftNav))setOnClickListener(本);
        ((按钮)findViewById(R.id.btnRightNav))setOnClickListener(本);
        ((ImageView的)findViewById(R.id.imageviewCamera))
                .setOnClickListener(本);
        ((ImageView的)findViewById(R.id.imageviewGallery))
                .setOnClickListener(本);
        ((TextView中)findViewById(R.id.txtAudioSong))setOnClickListener(本);
        ((TextView中)findViewById(R.id.txtVedioSong))setOnClickListener(本);

        字样的脸= Typeface.createFromAsset(getAssets()
                字体/ GeosansLight.ttf);
        ((TextView中)findViewById(R.id.txtHeading))setTypeface(面)。
        ((的EditText)findViewById(R.id.edtMessage))setTypeface(面)。
        ((TextView中)findViewById(R.id.txtHeading))的setText(发送邮报);

    }

    @覆盖
    公共无效结束(){
        super.finish();
        overridePendingTransition(R.anim.slide_in_left,R.anim.slide_out_right);
    }

    @覆盖
    公共无效的onClick(视图v){
        // TODO自动生成方法存根
        如果(v.getId()== R.id.btnLeftNav){
            this.finish();
        }否则,如果(v.getId()== R.id.btnRightNav){
            字符串strPostMessage =((的EditText)findViewById(R.id.edtMessage))
                    .getEditableText()的toString()修剪()。
            如果(strPostMessage.length()== 0){
                Toast.makeText(appContext,类型的信息。,Toast.LENGTH_LONG)
                        。显示();
            } 其他 {
                为messageType =文本;

            }

        }
        //这个按钮,点击我要上传图片到服务器
        否则如果(v.getId()== R.id.imageviewCamera){
            意图cameraIntent =新的意图(
                    android.provider.MediaStore.ACTION_IM​​AGE_CAPTURE);
            startActivityForResult(cameraIntent,1);
        }否则,如果(v.getId()== R.id.imageviewGallery){
            / *
             *意向意图=新的意图(Intent.ACTION_GET_CONTENT,NULL);
             * intent.setType(图像/ *); startActivityForResult(意向,2);
             * /
            selectImageFromGallery();
        }否则,如果(v.getId()== R.id.txtAudioSong){
            意向意图=新的意图(Intent.ACTION_GET_CONTENT,NULL);
            intent.setType(音频/ *);
            startActivityForResult(意向,3);
        }否则,如果(v.getId()== R.id.txtVedioSong){
            意向意图=新的意图(Intent.ACTION_GET_CONTENT,NULL);
            intent.setType(视频/ *);
            startActivityForResult(意向,4);
        }
    }



    公共字符串getRealPathFromURI(上下文的背景下,乌里contentUri){
        光标光标= NULL;
        尝试 {
            的String []凸出= {MediaStore.Images.Media.DATA};
            光标= context.getContentResolver()查询(contentUri,凸出,空,
                    NULL,NULL);
            INT与Column_Index =光标
                    .getColumnIndexOrThrow(MediaStore.Images.Media.DATA);
            cursor.moveToFirst();
            返回cursor.getString(Column_Index中);
        } 最后 {
            如果(光标!= NULL){
                cursor.close();
            }
        }
    }


    公共无效selectImageFromGallery(){
        意向意图=新的意图();
        intent.setType(图像/ *);
        intent.setAction(Intent.ACTION_GET_CONTENT);
        startActivityForResult(Intent.createChooser(意向,选择图片),
                PICK_IMAGE);
    }

    公共无效去codeFILE(字符串文件路径){
        //德code图像尺寸
        BitmapFactory.Options O =新BitmapFactory.Options();
        o.inJustDe codeBounds = TRUE;
        BitmapFactory.de codeFILE(文件路径,O);

        //我们希望新的大小扩展到
        最终诠释REQUIRED_SIZE = 1024;

        //找到正确的比例值。它应该是2的幂。
        INT width_tmp = o.outWidth,height_tmp = o.outHeight;
        int标= 1;
        而(真){
            如果(width_tmp< REQUIRED_SIZE和放大器;&安培; height_tmp< REQUIRED_SIZE)
                打破;
            width_tmp / = 2;
            height_tmp / = 2;
            规模* = 2;
        }

        //德code与inSampleSize
        BitmapFactory.Options O2 =新BitmapFactory.Options();
        o2.inSampleSize =规模;
        位= BitmapFactory.de codeFILE(文件路径,O2);
        如果(位图!= NULL){
            新ImageUploadTask()执行()。
        }

    }

    私人位图位图;

    @覆盖
    保护无效onActivityResult(INT申请code,INT结果code,意图数据){
        super.onActivityResult(要求code,因此code,数据);

        如果(要求code == PICK_IMAGE和放大器;&安培;结果code == RESULT_OK
                &功放;&安培;空!=数据){
            乌里selectedImage = data.getData();
            的String [] filePathColumn = {MediaStore.Images.Media.DATA};

            光标光标= getContentResolver()查询(selectedImage,
                    filePathColumn,NULL,NULL,NULL);
            cursor.moveToFirst();

            INT参数:columnIndex = cursor.getColumnIndex(filePathColumn [0]);
            字符串picturePath = cursor.getString(参数:columnIndex);
            cursor.close();

            德codeFILE(picturePath);

        }
    }

    类ImageUploadTask扩展的AsyncTask<虚空,虚空,字符串> {
        //私人字符串webAddressToPost =htt​​p://your-website-here.com;

        //私人ProgressDialog对话框;
        私人ProgressDialog对话框=新ProgressDialog(
                SendPostActivity.this);

        @覆盖
        在preExecute保护无效(){
            dialog.setMessage(上传...);
            dialog.show();
        }

        @覆盖
        保护字符串doInBackground(空... PARAMS){
            尝试 {
                HttpClient的HttpClient的=新DefaultHttpClient();
                HttpContext的localContext =新BasicHttpContext();
                HttpPost httpPost =新HttpPost(Constant.serverUrl
                        +PostComment);

                MultipartEntity实体=新MultipartEntity(
                        HttpMultipartMode.BROWSER_COMPATIBLE);

                ByteArrayOutputStream BOS =新ByteArrayOutputStream();
                bitmap.com preSS(比较pressFormat.JPEG,100,BOS);
                byte []的数据= bos.toByteArray();
                字符串文件= Base64.en codeToString(数据,Base64.DEFAULT);
                entity.addPart(文件,新StringBody(文件));
                entity.addPart(
                        用户帐号,
                        新StringBody(Utility.getShared preferences(appContext,
                                Constant.USER_ID)));
                entity.addPart(
                        MSG_ID
                        新StringBody(Utility.getShared preferences(appContext,
                                Constant.MESSAGE_ID)));
                entity.addPart(类,新StringBody(图像));

                httpPost.setEntity(实体);
                HTT presponse响应= httpClient.execute(httpPost,
                        localContext);
                的BufferedReader读卡器=新的BufferedReader(
                        新的InputStreamReader(
                                。response.getEntity()的getContent(),UTF-8));

                串sResponse = reader.readLine();
                如果(响应!= NULL){
                    finalImagePath = sResponse;
                }
                返回sResponse;
            }赶上(例外五){
                // 出了些问题。与服务器错误连接
                e.printStackTrace();
            }
            返回null;
        }

        @覆盖
        保护无效onPostExecute(字符串结果){
            dialog.dismiss();
            Toast.makeText(getApplicationContext(),文件上传,
                    Toast.LENGTH_LONG).show();
            System.out的
                    .println(文件上传////////////+ finalImagePath);
        }

     } // asyntask班结束


} // final类两端
 

下面是我的服务器API方法:

 函数PostComment()
{
  $ OBJ =新funcs_ code();
  $ obj->连接();
  $输出=;
  $ UID = mysql_real_escape_string($ _ REQUEST ['USER_ID']);
  $中旬= mysql_real_escape_string($ _ REQUEST ['MSG_ID']);
  $通讯=;
  $型=文本;
  如果(使用isset($ _ REQUEST ['型']))
  {
    $型= mysql_real_escape_string($ _ REQUEST ['型']);
  }
  如果(使用isset($ _ REQUEST ['评论']))
  {
    $通讯= mysql_real_escape_string($ _ REQUEST ['评论']);
  }
  $ SQL =SELECT * FROM`雇员`WHERE user_ID的='$ UID';
  $水库=的mysql_query($ SQL);
  如果(mysql_num_rows($水库)== 1)
  {
    $行= mysql_fetch_assoc($水库);
    $ SQL1 =SELECT * FROM`messages` WHERE MSG_ID ='$中间';
    $ RES1 =请求mysql_query($ SQL1);
    如果(mysql_num_rows($ RES1)== 1)
    {
      $ ROW1 = mysql_fetch_assoc($ RES1);
      如果($行['GROUP_ID'] == $ ROW1 ['的groupId'])
      {
          $状态= 1; // 1对此事发表评论
          $文件名=;

          如果(使用isset($ _ FILES ['文件'])及和放大器; is_array($ _ FILES ['文件']))
          {
            $ allowedExts =阵列(JPEG,JPG,MP3,MP4,3GP);
            $ TEMP =爆炸(,$ _FILES [文件] [名称]。);
            $延长=端($ TEMP);

            //
            //检查文件扩展名和放大器;大小UPTO 5 MB
            //

            如果(($ _FILES [文件] [型] ==图像/ JPG|| $ _FILES [文件] [型] ==为image / jpeg|| $ _FILES [文件] [型] ==音频/ MPEG
            || $ _FILES [文件] [型] ==视频/ 3GPP|| $ _FILES [fiile] [型] ==视频/ MP4)及和放大器; $ _FILES [文件] [大小]< 5242880&功放;&安培; in_array($扩展,$ allowedExts))
            {
              如果($ _FILES [文件] [错误] 0)
              {
                //回声返回code:。 $ _FILES [文件] [错误。 < BR>中;
                $输出=阵列(状态=>'错误','信息'=> $ _FILES [文件] [错误]);
                标题(内容类型:应用程序/ JSON);
                回声json_en code($输出);
                出口;
              }
              其他
              {
                  $文件名=时间()。$扩展。
                  move_uploaded_file($ _ FILES [文件] [tmp_name的值],上传/$文件名);
                  $文件名='/uploads/'.$fileName;
              }
            }
            其他
            {
               $输出=阵列(状态=>'错误','信息'=>中Invalid_File);
               标题(内容类型:应用程序/ JSON);
               回声json_en code($输出);
               出口;
            }

            如果($文件名='!'和;&安培;!$型=文本)
            {
                $通讯= $文件名;
            }

          }

          //
          //下面的条件用于检查,如果上传任何媒体和文件没有上传
          //
          如果($类型='文本'和;!&安培; $文件名==){
               $输出=阵列(状态=>'错误','信息'=>中请,指定文件的有效参数);
               标题(内容类型:应用程序/ JSON);
               回声json_en code($输出);
               出口;
          }

          //
          //在任何情况下注释不能留空
          //
          如果($通讯!=)
          {
              $平方=INSERT INTO`user_comment`(`user_id`,`msg_id`,`type`,`comment`,`status`)VALUES('$ UID','$中期','$类型','$通讯','$状态');

              如果(的mysql_query($ SQ))
                $输出=阵列(状态=>'成功','信息'=>中Comment_Success);
              其他
                $输出=阵列(状态=>'错误','信息'=>中Comment_Fail);

          }其他{
               $输出=阵列(状态=>'错误','信息'=>中评论不能为空);
               标题(内容类型:应用程序/ JSON);
               回声json_en code($输出);
               出口;
          }
          ///////////////////////////

      }// 组
      其他
      {
        // $输出='USER_GROUP不匹配;
        $输出=阵列(状态=>'错误','信息'=>中User_group_Not_match);
      }
    }
    其他
    {
      // $输出='无效MSG_ID;
      $输出=阵列(状态=>'错误','信息'=>中Invalid_Msg_id);
    }
  }
  其他
  {
    // $输出=无效USER_ID;
    $输出=阵列(状态=>'错误','信息'=>中Invalid_User);
  }
标题(内容类型:应用程序/ JSON);
回声json_en code($输出);
}
 

解决方案

该类型是错误的,应该是为image / jpeg 在这一行:

  entity.addPart(类,新StringBody(图像));
 

另外,您要发送您的文件作为基地64 EN codeD字符串?你确定的PHP code处理呢?通常你应该使用 FileBody 直接文件,但可以使用 ContentBody 字节数组。

修改

这是我如何上传一个文件中的 ByteArrayOutputStream

  ByteArrayOutputStream BOS =新ByteArrayOutputStream();
    bitmap.com preSS(Bitmap.Com pressFormat.JPEG,100,BOS);
    ContentBody contentPart =新ByteArrayBody(bos.toByteArray(),图像/ JPEG,file.jpg);
    mpEntity.addPart(文件,contentPart);
 

这是你将如何做到这一点与 FileBody

 文件f = ....
mpEntity.addPart(文件,新FileBody(F));
 

hi i am developing an application that needs to post some images in jpeg format to server in multi-part file form , i have written below given code for this but it gives following response,

01-15 00:32:14.119: I/System.out(7598): file is upload {"status":"error","message":"Please, Specify valid Parameter for file"}

please someone help me. Thanks in advance . Here is my activity code

public class SendPostActivity extends Activity implements OnClickListener {
    private Context appContext;
    private String messageType;
    HashMap<String, String> fileList = new HashMap<String, String>();
    public String finalImagePath = null;
    // number of images to select
    private static final int PICK_IMAGE = 1;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        // TODO Auto-generated method stub
        super.onCreate(savedInstanceState);
        overridePendingTransition(R.anim.slide_in_left, R.anim.slide_out_right);
        setContentView(R.layout.activity_send_post);
        overridePendingTransition(R.anim.slide_in_right, R.anim.slide_out_left);

        appContext = this;
        initComponent();
    }

    private void initComponent() {

        ((Button) findViewById(R.id.btnLeftNav)).setVisibility(View.VISIBLE);
        ((Button) findViewById(R.id.btnRightNav)).setVisibility(View.VISIBLE);
        ((Button) findViewById(R.id.btnRightNav))
                .setBackgroundResource(R.drawable.send_btn);
        ((Button) findViewById(R.id.btnLeftNav)).setOnClickListener(this);
        ((Button) findViewById(R.id.btnRightNav)).setOnClickListener(this);
        ((ImageView) findViewById(R.id.imageviewCamera))
                .setOnClickListener(this);
        ((ImageView) findViewById(R.id.imageviewGallery))
                .setOnClickListener(this);
        ((TextView) findViewById(R.id.txtAudioSong)).setOnClickListener(this);
        ((TextView) findViewById(R.id.txtVedioSong)).setOnClickListener(this);

        Typeface face = Typeface.createFromAsset(getAssets(),
                "fonts/GeosansLight.ttf");
        ((TextView) findViewById(R.id.txtHeading)).setTypeface(face);
        ((EditText) findViewById(R.id.edtMessage)).setTypeface(face);
        ((TextView) findViewById(R.id.txtHeading)).setText("Send Post");

    }

    @Override
    public void finish() {
        super.finish();
        overridePendingTransition(R.anim.slide_in_left, R.anim.slide_out_right);
    }

    @Override
    public void onClick(View v) {
        // TODO Auto-generated method stub
        if (v.getId() == R.id.btnLeftNav) {
            this.finish();
        } else if (v.getId() == R.id.btnRightNav) {
            String strPostMessage = ((EditText) findViewById(R.id.edtMessage))
                    .getEditableText().toString().trim();
            if (strPostMessage.length() == 0) {
                Toast.makeText(appContext, "Type message.", Toast.LENGTH_LONG)
                        .show();
            } else {
                messageType = "text";

            }

        }
        // on this button click i want to post images to server
        else if (v.getId() == R.id.imageviewCamera) {
            Intent cameraIntent = new Intent(
                    android.provider.MediaStore.ACTION_IMAGE_CAPTURE);
            startActivityForResult(cameraIntent, 1);
        } else if (v.getId() == R.id.imageviewGallery) {
            /*
             * Intent intent = new Intent(Intent.ACTION_GET_CONTENT, null);
             * intent.setType("image/*"); startActivityForResult(intent, 2);
             */
            selectImageFromGallery();
        } else if (v.getId() == R.id.txtAudioSong) {
            Intent intent = new Intent(Intent.ACTION_GET_CONTENT, null);
            intent.setType("audio/*");
            startActivityForResult(intent, 3);
        } else if (v.getId() == R.id.txtVedioSong) {
            Intent intent = new Intent(Intent.ACTION_GET_CONTENT, null);
            intent.setType("video/*");
            startActivityForResult(intent, 4);
        }
    }



    public String getRealPathFromURI(Context context, Uri contentUri) {
        Cursor cursor = null;
        try {
            String[] proj = { MediaStore.Images.Media.DATA };
            cursor = context.getContentResolver().query(contentUri, proj, null,
                    null, null);
            int column_index = cursor
                    .getColumnIndexOrThrow(MediaStore.Images.Media.DATA);
            cursor.moveToFirst();
            return cursor.getString(column_index);
        } finally {
            if (cursor != null) {
                cursor.close();
            }
        }
    }


    public void selectImageFromGallery() {
        Intent intent = new Intent();
        intent.setType("image/*");
        intent.setAction(Intent.ACTION_GET_CONTENT);
        startActivityForResult(Intent.createChooser(intent, "Select Picture"),
                PICK_IMAGE);
    }

    public void decodeFile(String filePath) {
        // Decode image size
        BitmapFactory.Options o = new BitmapFactory.Options();
        o.inJustDecodeBounds = true;
        BitmapFactory.decodeFile(filePath, o);

        // The new size we want to scale to
        final int REQUIRED_SIZE = 1024;

        // Find the correct scale value. It should be the power of 2.
        int width_tmp = o.outWidth, height_tmp = o.outHeight;
        int scale = 1;
        while (true) {
            if (width_tmp < REQUIRED_SIZE && height_tmp < REQUIRED_SIZE)
                break;
            width_tmp /= 2;
            height_tmp /= 2;
            scale *= 2;
        }

        // Decode with inSampleSize
        BitmapFactory.Options o2 = new BitmapFactory.Options();
        o2.inSampleSize = scale;
        bitmap = BitmapFactory.decodeFile(filePath, o2);
        if (bitmap != null) {
            new ImageUploadTask().execute();
        }

    }

    private Bitmap bitmap;

    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
        super.onActivityResult(requestCode, resultCode, data);

        if (requestCode == PICK_IMAGE && resultCode == RESULT_OK
                && null != data) {
            Uri selectedImage = data.getData();
            String[] filePathColumn = { MediaStore.Images.Media.DATA };

            Cursor cursor = getContentResolver().query(selectedImage,
                    filePathColumn, null, null, null);
            cursor.moveToFirst();

            int columnIndex = cursor.getColumnIndex(filePathColumn[0]);
            String picturePath = cursor.getString(columnIndex);
            cursor.close();

            decodeFile(picturePath);

        }
    }

    class ImageUploadTask extends AsyncTask<Void, Void, String> {
        // private String webAddressToPost = "http://your-website-here.com";

        // private ProgressDialog dialog;
        private ProgressDialog dialog = new ProgressDialog(
                SendPostActivity.this);

        @Override
        protected void onPreExecute() {
            dialog.setMessage("Uploading...");
            dialog.show();
        }

        @Override
        protected String doInBackground(Void... params) {
            try {
                HttpClient httpClient = new DefaultHttpClient();
                HttpContext localContext = new BasicHttpContext();
                HttpPost httpPost = new HttpPost(Constant.serverUrl
                        + "PostComment");

                MultipartEntity entity = new MultipartEntity(
                        HttpMultipartMode.BROWSER_COMPATIBLE);

                ByteArrayOutputStream bos = new ByteArrayOutputStream();
                bitmap.compress(CompressFormat.JPEG, 100, bos);
                byte[] data = bos.toByteArray();
                String file = Base64.encodeToString(data, Base64.DEFAULT);
                entity.addPart("file", new StringBody(file));
                entity.addPart(
                        "user_id",
                        new StringBody(Utility.getSharedPreferences(appContext,
                                Constant.USER_ID)));
                entity.addPart(
                        "msg_id",
                        new StringBody(Utility.getSharedPreferences(appContext,
                                Constant.MESSAGE_ID)));
                entity.addPart("type", new StringBody("image"));

                httpPost.setEntity(entity);
                HttpResponse response = httpClient.execute(httpPost,
                        localContext);
                BufferedReader reader = new BufferedReader(
                        new InputStreamReader(
                                response.getEntity().getContent(), "UTF-8"));

                String sResponse = reader.readLine();
                if (response != null) {
                    finalImagePath = sResponse;
                }
                return sResponse;
            } catch (Exception e) {
                // something went wrong. connection with the server error
                e.printStackTrace();
            }
            return null;
        }

        @Override
        protected void onPostExecute(String result) {
            dialog.dismiss();
            Toast.makeText(getApplicationContext(), "file uploaded",
                    Toast.LENGTH_LONG).show();
            System.out
                    .println("file is uploaded ////////////" + finalImagePath);
        }

     } // asyntask class ends 


} // final class ends 

Here is my server api method:

function PostComment()
{
  $obj = new funcs_code();
  $obj->connection();
  $output = "";  
  $uid = mysql_real_escape_string($_REQUEST['user_id']);
  $mid = mysql_real_escape_string($_REQUEST['msg_id']);
  $comm = "";
  $type = "text";
  if(isset($_REQUEST['type']))
  {
    $type = mysql_real_escape_string($_REQUEST['type']);
  }
  if(isset($_REQUEST['comment']))
  {
    $comm = mysql_real_escape_string($_REQUEST['comment']);
  }
  $sql = "SELECT * FROM `users` WHERE user_id = '$uid'";
  $res = mysql_query($sql);
  if(mysql_num_rows($res)==1)
  {
    $row = mysql_fetch_assoc($res);
    $sql1 = "SELECT * FROM `messages` WHERE msg_id = '$mid'";
    $res1 = mysql_query($sql1);
    if(mysql_num_rows($res1)==1)
    { 
      $row1 = mysql_fetch_assoc($res1);
      if($row['group_id'] == $row1['groupId'])
      {
          $status = 1; // 1 for comment
          $fileName = "";

          if(isset($_FILES['file']) && is_array($_FILES['file']))
          {
            $allowedExts = array("jpeg", "jpg", "mp3", "mp4", "3gp");
            $temp = explode(".", $_FILES["file"]["name"]);
            $extension = end($temp);

            //
            //Check File Extension & Size UPTO 5 MB
            //

            if (( $_FILES["file"]["type"] == "image/jpg"  || $_FILES["file"]["type"] == "image/jpeg" || $_FILES["file"]["type"] == "audio/mpeg"
            || $_FILES["file"]["type"] == "video/3gpp" || $_FILES["fiile"]["type"] == "video/mp4" ) && $_FILES["file"]["size"] < 5242880 && in_array($extension, $allowedExts))
            {
              if ($_FILES["file"]["error"] > 0)
              {
                //echo "Return Code: " . $_FILES["file"]["error"] . "<br>";
                $output = array('status' => 'error','message' => $_FILES["file"]["error"]);
                header('content-type: application/json');
                echo json_encode($output);
                exit;
              }
              else
              {                
                  $fileName = time().".$extension";
                  move_uploaded_file($_FILES["file"]["tmp_name"], "uploads/". $fileName);
                  $fileName = '/uploads/'.$fileName; 
              }
            }
            else
            {
               $output = array('status' => 'error','message' => "Invalid_File");
               header('content-type: application/json');
               echo json_encode($output);
               exit;
            }

            if($fileName != '' && $type != 'text')
            {
                $comm = $fileName;
            }

          }

          //
          //Below Condition Used to check, If uploading any media and File not Uploaded
          //
          if($type != 'text' && $fileName == ""){         
               $output = array('status' => 'error','message' => "Please, Specify valid Parameter for file");
               header('content-type: application/json');
               echo json_encode($output);
               exit;
          }

          //
          //In Any Case Comment can not be left blank
          //
          if($comm != "")
          {
              $sq = "INSERT INTO `user_comment`(`user_id`,`msg_id`,`type`,`comment`,`status`) VALUES('$uid','$mid','$type','$comm','$status')";

              if(mysql_query($sq))
                $output = array('status' => 'success','message' => "Comment_Success");
              else
                $output = array('status' => 'error','message' => "Comment_Fail");

          }else{
               $output = array('status' => 'error','message' => "Comment Can not be blank");
               header('content-type: application/json');
               echo json_encode($output);
               exit;
          }
          ///////////////////////////  

      }// group
      else
      {
        //$output = 'user_group not match';
        $output = array('status' => 'error','message' => "User_group_Not_match");
      }
    }
    else
    {
      //$output = 'invalid msg_id';
      $output = array('status' => 'error','message' => "Invalid_Msg_id");
    }
  }
  else
  {
    //$output = "invalid user_id";
    $output = array('status' => 'error','message' => "Invalid_User");
  }
header('content-type: application/json');
echo json_encode($output);
}

解决方案

The type is wrong, should be image/jpeg in this line:

entity.addPart("type", new StringBody("image"));

Also, you are sending your File as a Base 64 encoded string?? Are you sure the php code handles that? Usually you are supposed to use FileBody with the file directly, but you can use a ContentBody for byte arrays.

Edit

This is how I upload a file with a ByteArrayOutputStream

    ByteArrayOutputStream bos = new ByteArrayOutputStream();
    bitmap.compress(Bitmap.CompressFormat.JPEG, 100, bos);
    ContentBody contentPart = new ByteArrayBody(bos.toByteArray(), "image/jpeg", "file.jpg");
    mpEntity.addPart("file", contentPart);

This is how you would do it with a FileBody

File f = ....
mpEntity.addPart("file", new FileBody(f));

这篇关于上传图片JPEG格式的多部分文件在android的服务器的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆