图片没有上传

时间:2015-08-25 03:30:23

标签: php android mysql image

当我尝试点击注册按钮时,数据将被上传到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);
            }
        });
    }
}

3 个答案:

答案 0 :(得分:0)

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

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

您无法将 $ image = $ _POST [&#34;图像&#34;] 用于图片,仅适用于文字。

感谢

答案 1 :(得分:0)

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

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!";
}
}
?>

由于 希望这会对你有所帮助。

答案 2 :(得分:0)

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

像这个例子一样使用它:

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