将图像上传到服务器并将图像路径存储在mysql数据库中

时间:2014-03-29 15:17:01

标签: php android mysql image

我按照此tutorial将图片上传到服务器。

现在我的问题是如何在上传完成后修改代码以将图像路径另外保存到MySql数据库中?请帮助解决此问题。

对于completition,我正在显示当前代码以将图像上传到服务器:

MainActivity.java:

public class MainActivity extends Activity implements OnClickListener {

    private TextView messageText;
    private Button uploadButton, btnselectpic;
    private ImageView imageview;
    private int serverResponseCode = 0;
    private ProgressDialog dialog = null;

    private String upLoadServerUri = null;
    private String imagepath = null;

    @Override
    public void onCreate(Bundle savedInstanceState) {

        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);

        uploadButton = (Button) findViewById(R.id.uploadButton);
        btnselectpic = (Button) findViewById(R.id.button_selectpic);
        messageText = (TextView) findViewById(R.id.messageText);
        imageview = (ImageView) findViewById(R.id.imageView_pic);

        btnselectpic.setOnClickListener(this);
        uploadButton.setOnClickListener(this);
        upLoadServerUri = "http://10.0.2.2/uploads/UploadToServer.php";
        ImageView img = new ImageView(this);

    }

    @Override
    public void onClick(View arg0) {
        if (arg0 == btnselectpic) {
            Intent intent = new Intent();
            intent.setType("image/*");
            intent.setAction(Intent.ACTION_GET_CONTENT);
            startActivityForResult(
                    Intent.createChooser(intent, "Complete action using"), 1);
        } else if (arg0 == uploadButton) {

            dialog = ProgressDialog.show(MainActivity.this, "",
                    "Uploading file...", true);
            messageText.setText("uploading started.....");
            new Thread(new Runnable() {
                public void run() {

                    uploadFile(imagepath);

                }
            }).start();
        }

    }

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

        if (requestCode == 1 && resultCode == RESULT_OK) {
            // Bitmap photo = (Bitmap) data.getData().getPath();

            Uri selectedImageUri = data.getData();
            imagepath = getPath(selectedImageUri);
            Bitmap bitmap = BitmapFactory.decodeFile(imagepath);
            imageview.setImageBitmap(bitmap);
            messageText.setText("Uploading file path:" + imagepath);

        }
    }

    public String getPath(Uri uri) {
        String[] projection = { MediaStore.Images.Media.DATA };
        Cursor cursor = managedQuery(uri, projection, null, null, null);
        int column_index = cursor
                .getColumnIndexOrThrow(MediaStore.Images.Media.DATA);
        cursor.moveToFirst();
        return cursor.getString(column_index);
    }

    public int uploadFile(String sourceFileUri) {

        String fileName = sourceFileUri;

        HttpURLConnection conn = null;
        DataOutputStream dos = null;
        String lineEnd = "\r\n";
        String twoHyphens = "--";
        String boundary = "*****";
        int bytesRead, bytesAvailable, bufferSize;
        byte[] buffer;
        int maxBufferSize = 1 * 1024 * 1024;
        File sourceFile = new File(sourceFileUri);

        if (!sourceFile.isFile()) {

            dialog.dismiss();

            Log.e("uploadFile", "Source File not exist :" + imagepath);

            runOnUiThread(new Runnable() {
                public void run() {
                    messageText.setText("Source File not exist :" + imagepath);
                }
            });

            return 0;

        } else {
            try {

                // open a URL connection to the Servlet
                FileInputStream fileInputStream = new FileInputStream(
                        sourceFile);
                URL url = new URL(upLoadServerUri);

                // Open a HTTP connection to the URL
                conn = (HttpURLConnection) url.openConnection();
                conn.setDoInput(true); // Allow Inputs
                conn.setDoOutput(true); // Allow Outputs
                conn.setUseCaches(false); // Don't use a Cached Copy
                conn.setRequestMethod("POST");
                conn.setRequestProperty("Connection", "Keep-Alive");
                conn.setRequestProperty("ENCTYPE", "multipart/form-data");
                conn.setRequestProperty("Content-Type",
                        "multipart/form-data;boundary=" + boundary);
                conn.setRequestProperty("uploaded_file", fileName);

                dos = new DataOutputStream(conn.getOutputStream());

                dos.writeBytes(twoHyphens + boundary + lineEnd);
                dos.writeBytes("Content-Disposition: form-data; name=\"uploaded_file\";filename=\""
                        + fileName + "\"" + lineEnd);

                dos.writeBytes(lineEnd);

                // create a buffer of maximum size
                bytesAvailable = fileInputStream.available();

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

                // read file and write it into form...
                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);

                }

                // send multipart form data necesssary after file data...
                dos.writeBytes(lineEnd);
                dos.writeBytes(twoHyphens + boundary + twoHyphens + lineEnd);

                // Responses from the server (code and message)
                serverResponseCode = conn.getResponseCode();
                String serverResponseMessage = conn.getResponseMessage();

                Log.i("uploadFile", "HTTP Response is : "
                        + serverResponseMessage + ": " + serverResponseCode);

                if (serverResponseCode == 200) {

                    runOnUiThread(new Runnable() {
                        public void run() {
                            String msg = "File Upload Completed.\n\n See uploaded file here : \n\n"
                                    + " F:/wamp/wamp/www/uploads";
                            messageText.setText(msg);
                            Toast.makeText(MainActivity.this,
                                    "File Upload Complete.", Toast.LENGTH_SHORT)
                                    .show();
                        }
                    });
                }

                // close the streams //
                fileInputStream.close();
                dos.flush();
                dos.close();

            } catch (MalformedURLException ex) {

                dialog.dismiss();
                ex.printStackTrace();

                runOnUiThread(new Runnable() {
                    public void run() {
                        messageText
                                .setText("MalformedURLException Exception : check script url.");
                        Toast.makeText(MainActivity.this,
                                "MalformedURLException", Toast.LENGTH_SHORT)
                                .show();
                    }
                });

                Log.e("Upload file to server", "error: " + ex.getMessage(), ex);
            } catch (Exception e) {

                dialog.dismiss();
                e.printStackTrace();

                runOnUiThread(new Runnable() {
                    public void run() {
                        messageText.setText("Got Exception : see logcat ");
                        Toast.makeText(MainActivity.this,
                                "Got Exception : see logcat ",
                                Toast.LENGTH_SHORT).show();
                    }
                });
                Log.e("Upload file to server Exception",
                        "Exception : " + e.getMessage(), e);
            }
            dialog.dismiss();
            return serverResponseCode;

        } // End else block
    }

}

将图像存储在服务器上的PHP文件:

<?php  
    $file_path = "uploads/";

    $file_path = $file_path . basename( $_FILES['uploaded_file']['name']);
    if(move_uploaded_file($_FILES['uploaded_file']['tmp_name'], $file_path)) {
        echo "success";
    } else{
        echo "fail";
    }
 ?>

2 个答案:

答案 0 :(得分:4)

SQL:

CREATE TABLE `uploads` (
  `id` int(11) NOT NULL AUTO_INCREMENT,
  `filename` varchar(255) NOT NULL,
  `path` varchar(255) NOT NULL,
  PRIMARY KEY (`id`)
) ENGINE=MyISAM DEFAULT CHARSET=utf8 AUTO_INCREMENT=1 ;

PHP:

$file_path = "uploads/";

$file_path = $file_path . basename( $_FILES['uploaded_file']['name']);
if(move_uploaded_file($_FILES['uploaded_file']['tmp_name'], $file_path)) {
  // replace $host,$username,$password,$dbname with real info
  $link=mysqli_connect($host,$username,$password,$dbname);
  mysqli_query($link,"INSERT INTO `files` (filename,path) VALUES ('".$_FILES['uploaded_file']['tmp_name']."','".$file_path."')") or trigger_error($link->error."[ $sql]");
  mysqli_close($link);

} else{
    echo "fail";

答案 1 :(得分:0)

package com.example.jojo.traveldiary;
import android.content.Intent;
import android.database.Cursor;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.net.Uri;
import android.os.Bundle;
import android.os.Environment;
import android.provider.MediaStore;
import android.support.design.widget.TextInputLayout;
import android.support.v7.app.AppCompatActivity;
import android.support.v7.widget.Toolbar;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.widget.ArrayAdapter;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.ProgressBar;
import android.widget.Spinner;
import android.widget.TextView;
import android.widget.Toast;

import com.loopj.android.http.AsyncHttpClient;
import com.loopj.android.http.JsonHttpResponseHandler;
import com.loopj.android.http.RequestParams;

import org.apache.http.Header;
import org.json.JSONException;
import org.json.JSONObject;

import java.io.File;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.text.SimpleDateFormat;
import java.util.Calendar;
import java.util.Date;
public class Add_Trip_Details extends AppCompatActivity 
    {
      EditText title;
      EditText date;
      EditText time;
EditText discription;
TextView heading;
ImageView browseimg;
ImageView captureimg;
ImageView image;
Spinner l;
String imgphoto=null;
String placenameid;
String tripplace;
String tripdate;
ProgressBar progress;
private  Toolbar toolbar;
TextInputLayout titleerror;
TextInputLayout descriptionerror;
int a=0;
@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_add__trip__details);
    placenameid=getIntent().getStringExtra("key");
    tripplace=getIntent().getStringExtra("pey");
    tripdate=getIntent().getStringExtra("dey");
    String currentdate=new SimpleDateFormat("yyyy-MM-dd").format(new Date());
    Calendar c = Calendar.getInstance();
    SimpleDateFormat sdf = new SimpleDateFormat("hh:mm a");
    String strDate = sdf.format(c.getTime());
    heading= (TextView) findViewById(R.id.heading);
    heading.setText("Add  Details To Your "+tripplace+" Trip");
    titleerror= (TextInputLayout) findViewById(R.id.view);
    descriptionerror= (TextInputLayout) findViewById(R.id.view1);
    title= (EditText) findViewById(R.id.editText12);
    date= (EditText) findViewById(R.id.editText13);
    time= (EditText) findViewById(R.id.editText14);
    discription= (EditText) findViewById(R.id.editText15);
    browseimg= (ImageView) findViewById(R.id.imageView);
    captureimg= (ImageView) findViewById(R.id.imageView2);
    image= (ImageView) findViewById(R.id.imageView3);
    progress= (ProgressBar) findViewById(R.id.progressBar4);
    progress.setVisibility(View.INVISIBLE);
    date.setText(currentdate);
    time.setText(strDate);
    l=(Spinner) findViewById(R.id.spinner);
    String a[]={"Private","Public"};
    ArrayAdapter<String> adapter=new ArrayAdapter<String>(this,android.R.layout.simple_list_item_1,a);
    l.setAdapter(adapter);
    toolbar= (Toolbar) findViewById(R.id.include);
    setSupportActionBar(toolbar);


}

public  void browseImg(View view)
{
   Intent in=new Intent(Intent.ACTION_PICK,android.provider.MediaStore.Images.Media.EXTERNAL_CONTENT_URI);
   startActivityForResult(in, 1);
   // Intent intent = new Intent();
    //intent.setType("image/*");
    //intent.putExtra(Intent.EXTRA_ALLOW_MULTIPLE, true);
    //intent.setAction(Intent.ACTION_GET_CONTENT);
    //startActivityForResult(Intent.createChooser(intent,"Select Picture"), 1);
}
public  void  captureImg(View view)
{
    Intent in=new Intent(android.provider.MediaStore.ACTION_IMAGE_CAPTURE);
    startActivityForResult(in, 2);
}
public  void submit()
{

   String status= l.getSelectedItem().toString();
    String titlestring=title.getText().toString();
    String descriptionstring=discription.getText().toString();
    String datestring=date.getText().toString();
    String timestring=time.getText().toString();

    //Add_Trip_Details_AsyncTask asynctask=new Add_Trip_Details_AsyncTask(this,status,titlestring,descriptionstring,placenameid);
    //asynctask.execute("");
    if(titlestring.equals(""))
    {
        titleerror.setErrorEnabled(true);
        titleerror.setError("Enter a titile ");
        a=1;

    }
    else
    {
        titleerror.setErrorEnabled(false);
        a=0;
    }
   if(descriptionstring.equals(""))
    {
        descriptionerror.setErrorEnabled(true);
        descriptionerror.setError("Enter Discription ");
        a=1;
    }
   else
   {
       titleerror.setErrorEnabled(false);
       a=0;
   }
   /* if(imgphoto.equals(""))
    {
        Toast.makeText(this, "insert an image", Toast.LENGTH_LONG).show();
        a=1;
    }
    else
    {

        a=0;
    }*/

    if(a==0)
    {
        progress.setVisibility(View.VISIBLE);
    AsyncHttpClient client=new AsyncHttpClient();
    RequestParams params=new RequestParams();
    params.put("title",titlestring);
    params.put("discription", descriptionstring);
    params.put("status", status);
    params.put("p_id", placenameid);
        params.put("trip_date", datestring);
        params.put("cre_time", timestring);
    try {
        params.put("im_name", new File(imgphoto));
    } catch (FileNotFoundException e) {
        e.printStackTrace();
    }
  //  Log.e("img path ", imgphoto.toString());
  client.post(AppConstant.WEB_URL+"trip_details.php", params, new JsonHttpResponseHandler() {
        @Override
        public void onSuccess(int statusCode, Header[] headers, JSONObject response) {
            super.onSuccess(statusCode, headers, response);

            try {

                String status = response.getString("status");
                Toast.makeText(getApplicationContext(), status, Toast.LENGTH_LONG).show();
                progress.setVisibility(View.INVISIBLE);
                finish();
                Intent in = new Intent(Add_Trip_Details.this, View_Trip_Details.class);
                in.putExtra("iey", placenameid);
                in.putExtra("pey", tripplace);
                in.putExtra("dey", tripdate);
                startActivity(in);
            } catch (JSONException e) {
                e.printStackTrace();
            }

        }

        @Override
        public void onFailure(int statusCode, Header[] headers, String responseString, Throwable throwable) {
            super.onFailure(statusCode, headers, responseString, throwable);
            Toast.makeText(getApplicationContext(), "faild", Toast.LENGTH_LONG).show();
            progress.setVisibility(View.INVISIBLE);
        }

        @Override
        public void onStart() {
            super.onStart();
        }

        @Override
        public void onFinish() {
            super.onFinish();
        }
    });
        /*client.post("http://192.168.1.11/Travel_Dairy/trip_details.php", params, new AsyncHttpResponseHandler() {


            @Override
            public void onSuccess(int statusCode, Header[] headers, byte[] responseBody) {
                Toast.makeText(getApplicationContext(), "sucess", Toast.LENGTH_LONG).show();
                progress.setVisibility(View.INVISIBLE);
                finish();
                Intent in = new Intent(Add_Trip_Details.this, View_Trip_Details.class);
                in.putExtra("iey", placenameid);
                in.putExtra("pey", tripplace);
                in.putExtra("dey", tripdate);
                startActivity(in);
                finish();
                // Intent in = new Intent(ViewOREdit.this, Home.class);
                // startActivity(in);

            }

            @Override
            public void onFailure(int statusCode, Header[] headers, byte[] responseBody, Throwable error) {
                Toast.makeText(getApplicationContext(), "faild", Toast.LENGTH_LONG).show();

            }
        });*/
   //finish();
    }

}

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

    Calendar calender=Calendar.getInstance();
    Long lo=calender.getTimeInMillis();

    super.onActivityResult(requestCode, resultCode, data);
    if(requestCode==2)
    {
      try
      {
          Bitmap bt=(Bitmap) data.getExtras().get("data");
          image.setImageBitmap(bt);
          savePhoto(bt,lo+".jpg");
      }
      catch(Exception e)
      {
          e.printStackTrace();
      }

    }
    else if(requestCode==1)
    {
try
 {
  Uri uri=data.getData();
  String[] path={MediaStore.Images.Media.DATA};
  Cursor cur=getContentResolver().query(uri, path, null, null, null);
  cur.moveToFirst();
  int a=cur.getColumnIndex(path[0]);
  String c=cur.getString(a);
  cur.close();
  image.setImageBitmap(BitmapFactory.decodeFile(c));
  savePhoto(BitmapFactory.decodeFile(c),lo+".jpg");
}
catch(Exception e)
 {
  e.printStackTrace();
 }



    }
}
public void savePhoto(Bitmap imagetosave,String filename) {
    File direct=new File(Environment.getExternalStorageDirectory()+"MyTravelDiary");
    if(!direct.exists())
    {
        File newdirectory=new File("/sdcard/MyTravelDiary");
        newdirectory.mkdirs();

    }
    File file=new File(new File("/sdcard/MyTravelDiary"),filename);
    if(file.exists())
    {
        file.delete();
    }
    try
    {
        FileOutputStream fo=new FileOutputStream(file);
        imagetosave.compress(Bitmap.CompressFormat.JPEG, 100, fo);
        fo.flush();
        fo.close();
        imgphoto="/sdcard/MyTravelDiary/"+filename;
    }
    catch(Exception e)
    {
        e.printStackTrace();
    }

}

@Override
public boolean onCreateOptionsMenu(Menu menu) {
    // Inflate the menu; this adds items to the action bar if it is present.
    getMenuInflater().inflate(R.menu.menu_add__trip__details, menu);
    return true;
}

@Override
public boolean onOptionsItemSelected(MenuItem item) {
    // Handle action bar item clicks here. The action bar will
    // automatically handle clicks on the Home/Up button, so long
    // as you specify a parent activity in AndroidManifest.xml.
    int id = item.getItemId();
    //noinspection SimplifiableIfStatement
    if (id == R.id.submit) {
        submit();
        return true;
    }

    return super.onOptionsItemSelected(item);
}

}