【问题标题】:Image not getting uploaded图片没有上传
【发布时间】:2015-08-25 03:30:22
【问题描述】:

当我尝试点击注册按钮时,数据正在上传到 mysql 表中,但我发送的图像没有上传到服务器上。我在服务器中创建了一个文件夹,所有图像都将存储在其中。并且路径在PHP文件中给出。

PHP 文件:

<?php
$image= $_POST["image"];

$decodedImage=base64_decode("$image");

file_put_contents("pictures/" . $image . ".JPG", $decodedImage);
?>

Register.java

public class Register extends Activity implements View.OnClickListener{

    EditText etName, etAge, etUsername, etPassword;
    Button bRegister,bUpload;
    ImageView imageUp;
    private static final int RESULT_IMAGE=1;
    private static final String SERVER_ADDRESS="http://swapnilsaraf.esy.es/";


    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_register);

        etName = (EditText) findViewById(R.id.etName);
        etAge = (EditText) findViewById(R.id.etAge);
        etUsername = (EditText) findViewById(R.id.etUsername);
        etPassword = (EditText) findViewById(R.id.etPassword);
        bRegister = (Button) findViewById(R.id.bRegister);

        imageUp=(ImageView)findViewById(R.id.upImage);

        bRegister.setOnClickListener(this);

        imageUp.setOnClickListener(this);
    }

    @Override
    public void onClick(View v) {
        switch (v.getId()) {
            case R.id.bRegister:
                String name = etName.getText().toString();
                String username = etUsername.getText().toString();
                String password = etPassword.getText().toString();
                int age = Integer.parseInt(etAge.getText().toString());
                Bitmap image=((BitmapDrawable)imageUp.getDrawable()).getBitmap();
                User user = new User(name, age, username, password);
                registerUser(user);

                 uploadImage ui=new uploadImage(image);
                 ui.execute();

                break;


            case R.id.upImage:
                Intent i=new Intent(Intent.ACTION_PICK, MediaStore.Images.Media.EXTERNAL_CONTENT_URI);
                startActivityForResult(i,RESULT_IMAGE);

                Toast.makeText(getApplicationContext(),"Selecting Image",Toast.LENGTH_LONG).show();
                break;

        }
    }


    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        if(requestCode==RESULT_IMAGE && resultCode==RESULT_OK && data!=null){
            Uri selectedImage=data.getData();
            imageUp.setImageURI(selectedImage);

            Toast.makeText(getApplicationContext(),"Image Selected",Toast.LENGTH_LONG).show();
        }
    }


    public class uploadImage extends AsyncTask<Void, Void,Void>{

        Bitmap image;

        public uploadImage(Bitmap image){
            this.image=image;
        }

        @Override
        protected Void doInBackground(Void... arg0) {

            ByteArrayOutputStream byteArrayOutputStream=new ByteArrayOutputStream();
            image.compress(Bitmap.CompressFormat.JPEG,100,byteArrayOutputStream);
            String encodedImage= Base64.encodeToString(byteArrayOutputStream.toByteArray(),Base64.DEFAULT);

            ArrayList<NameValuePair> dataToSend=new ArrayList<NameValuePair>();

            dataToSend.add(new BasicNameValuePair("image",encodedImage));
            HttpParams httpRequestParams=getHttpRequestParams();
            HttpClient client= new DefaultHttpClient(httpRequestParams);

            HttpPost post1=new HttpPost(SERVER_ADDRESS + "upload.php");
            try{
                 post1.setEntity(new UrlEncodedFormEntity(dataToSend));
                 client.execute(post1);
            }
            catch(Exception e){
                e.printStackTrace();
            }

            return null;

        }

        @Override
        protected void onPostExecute(Void result) {
            // TODO Auto-generated method stub
            super.onPostExecute(result);
            a
            Toast.makeText(getApplicationContext(), "Image uploaded", Toast.LENGTH_SHORT).show();
        }

    }

    private HttpParams  getHttpRequestParams(){
        HttpParams httpRequestParams=new BasicHttpParams();
        HttpConnectionParams.setConnectionTimeout(httpRequestParams,1000*30);
        HttpConnectionParams.setSoTimeout(httpRequestParams,1000*30);
        return httpRequestParams;
    }

    private void registerUser(User user) {
        ServerRequests serverRequest = new ServerRequests(this);
        serverRequest.storeUserDataInBackground(user, new GetUserCallback() {
            @Override
            public void done(User returnedUser) {
                Intent loginIntent = new Intent(Register.this, Login.class);
                startActivity(loginIntent);
            }
        });
    }
}

【问题讨论】:

    标签: php android mysql image


    【解决方案1】:

    要在 PHP 中上传图片,请使用以下代码

    <?php
    $photoname=$_FILES['photo']['name'];
    $tmp_name=$_FILES['photo']['tmp_name'];
    $destinationpath="img/".$photoname;
    $moveimage=move_uploaded_file($tmp_name,$destinationpath);
    ?>
    

    您不能将 $image= $_POST["image"] 用于图像,它只能用于文本。

    谢谢

    【讨论】:

      【解决方案2】:

      我正在使用以下代码上传我的图片,您可以从此代码中获得帮助。

      This is my page add_product.php from where i am getting image url.
      
      <form action="add_product1.php" method="post" enctype="multipart/form-data">
      <table><tr><td>Category</td>
      <td><select id="cate" name="cate">
      <option>---Select one---</option>
      <?php while($row=mysql_fetch_array($result)){?>
      <option>
      <?php echo $row['cate_add_item'];?>
      </option>
      <?php }?>
      </select>
      </td> 
      </tr>
      <tr>
      <td>Product name</td>
      <td><input type="text" id="pro_name" name="pro_name" /></td>
      </tr>
      <tr>
      <td>Product Desc</td>
      <td><textarea cols="10" rows="10" id="pro_desc" name="pro_desc"></textarea>
      </td>
      </tr>
      <tr>
      <td>Product Image</td>
      <td><input type="file" id="pro_img" name="pro_img" /></td>
      </tr>
      <tr>
      <td>Actual Cost</td>
      <td><input type="text" id="pro_cost" name="pro_cost" /></td>
      </tr>
      <tr>
      <td>Discount</td>
      <td><select id="pro_dis" name="pro_dis" onchange="return abc(this.value)">
      <option>Select</option>
      <option>10</option>
      <option>20</option>
      <option>30</option>
      <option>40</option>
      <option>50</option>
      <option>60</option>
      </select></td>
      </tr>
      <tr>
      <td>Selling Price</td>
      <td><input type="text" id="pro_price" name="pro_price" /></td>
      </tr>
      <tr>
      <td colspan="2"><input type="submit" value="ADD" /></td>
      </tr>
      </table>
      </form>
      

      表单提交后,我的表单被重定向到 add_product1.php

      <?php
      $con=mysql_connect('localhost','root','');
      if(!$con)
      {
      die('could not connect' .mysql_error());
      }
      mysql_select_db("jaswinder", $con);
      
      $pro_cate=$_POST['cate'];
      $query="select cate_id from category where cate_add_item='$pro_cate'";
      $result=mysql_query($query);
      if($result)
      {
      
      $row=mysql_fetch_array($result);
      $cid=$row['cate_id'];
      $pname=$_POST['pro_name'];
      $pdesc=$_POST['pro_desc'];
      $pactual=$_POST['pro_cost'];
      $pdis=$_POST['pro_dis'];
      $pprice=$_POST['pro_price'];
      $pimage=$_FILES['pro_img']['name'];
      $temp=$_FILES['pro_img']['tmp_name']."<br>";
      $path="Img/".$pimage;
      move_uploaded_file($_FILES['pro_img']['tmp_name'],$path);
      
      $insert="insert into product(pro_catagory,cate_id,pro_name,pro_des,pro_image,pro_actual,pro_dis,pro_price) values('$pro_cate','$cid','$pname','$pdesc','$pimage','$pactual','$pdis','$pprice')";
      $reslt=mysql_query($insert);
      if(empty($reslt))
      {
      
          header('location:add_product.php');
      }
          else
      {
          echo "Category Added Succesfully!";
      }
      }
      ?>
      

      谢谢 希望这会对你有所帮助。

      【讨论】:

        【解决方案3】:

        file_put_contents 不起作用的原因是因为您使用二进制 base64 编码字符串 $image 来定义要写入的文件名。

        像这个例子一样使用它:

        $filename = "image1";
        file_put_contents("pictures/" . $filename . ".JPG", $decodedImage);
        

        【讨论】:

        • 我应该对 java 文件进行哪些更改?
        • 好吧,我不是 Java 专家,但我想如果你想要原始文件名,你应该传递它。除此之外,我认为这看起来不错。你试过我的例子吗?
        • 是的,但它返回的是文本文件而不是图像
        • 我能想到的最后一件事是尝试 stream_get_contents() 并使用 fwrite() 写入文件
        猜你喜欢
        • 1970-01-01
        • 2011-09-11
        • 2023-03-17
        • 2018-02-17
        • 1970-01-01
        • 2018-05-02
        • 2021-08-14
        • 2012-11-05
        • 2014-04-01
        相关资源
        最近更新 更多