当前位置: 首页 > 知识库问答 >
问题:

将图像上传到服务器,并将带有文本值的路径存储到MySQL中

洪河
2023-03-14

我仍然是初学者的Andorid编程,并需要一些帮助以下:

我现在有两个代码,第一个将图像上传到服务器,并将路径存储到MySQL表中。第二个代码将2个EditText字段值存储到MySQL数据库表中。我真正想要的是将这两个代码结合起来,这样就可以将一个图像上传到服务器,然后将带有2个EditText字段值的关联字符串路径一次存储到MySQL数据库表中。

1.)为了上传图像并将字符串路径存储到MySQL表中,我有以下代码:

上传图像到服务器(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端):

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

2.)对于插入EditText值从Android到MySQL数据库我有以下代码:

-MySQL数据库表插入值(JAVA端):

public class MainActivity extends Activity {

    String name;
    String id;
    InputStream is=null;
    String result=null;
    String line=null;
    int code;

    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);

        final EditText e_id=(EditText) findViewById(R.id.editText1);
        final EditText e_name=(EditText) findViewById(R.id.editText2);
        Button insert=(Button) findViewById(R.id.button1);

        insert.setOnClickListener(new View.OnClickListener() {

        @Override
        public void onClick(View v) {
            // TODO Auto-generated method stub

            id = e_id.getText().toString();
            name = e_name.getText().toString();

            insert();
        }
    });
    }

    public void insert()
    {
        ArrayList<NameValuePair> nameValuePairs = new ArrayList<NameValuePair>();

    nameValuePairs.add(new BasicNameValuePair("id",id));
    nameValuePairs.add(new BasicNameValuePair("name",name));

        try
        {
        HttpClient httpclient = new DefaultHttpClient();
            HttpPost httppost = new HttpPost("http://10.0.2.2/insert.php");
            httppost.setEntity(new UrlEncodedFormEntity(nameValuePairs));
            HttpResponse response = httpclient.execute(httppost); 
            HttpEntity entity = response.getEntity();
            is = entity.getContent();
            Log.e("pass 1", "connection success ");
    }
        catch(Exception e)
    {
            Log.e("Fail 1", e.toString());
            Toast.makeText(getApplicationContext(), "Invalid IP Address",
            Toast.LENGTH_LONG).show();
    }     

        try
        {
            BufferedReader reader = new BufferedReader
            (new InputStreamReader(is,"iso-8859-1"),8);
            StringBuilder sb = new StringBuilder();
            while ((line = reader.readLine()) != null)
        {
                sb.append(line + "\n");
            }
            is.close();
            result = sb.toString();
        Log.e("pass 2", "connection success ");
    }
        catch(Exception e)
    {
            Log.e("Fail 2", e.toString());
    }     

    try
    {
            JSONObject json_data = new JSONObject(result);
            code=(json_data.getInt("code"));

            if(code==1)
            {
        Toast.makeText(getBaseContext(), "Inserted Successfully",
            Toast.LENGTH_SHORT).show();
            }
            else
            {
         Toast.makeText(getBaseContext(), "Sorry, Try Again",
            Toast.LENGTH_LONG).show();
            }
    }
    catch(Exception e)
    {
            Log.e("Fail 3", e.toString());
    }
    }

    @Override
    public boolean onCreateOptionsMenu(Menu menu) {
        getMenuInflater().inflate(R.menu.activity_main, menu);
        return true;
    }    
}

-将值插入MySQL数据库表(PHP端):

<?php
    $host='127.0.0.1';
    $uname='root';
    $pwd='password';
    $db="android";

    $con = mysql_connect($host,$uname,$pwd) or die("connection failed");
    mysql_select_db($db,$con) or die("db selection failed");

    $id=$_REQUEST['id'];
    $name=$_REQUEST['name'];

    $flag['code']=0;

    if($r=mysql_query("insert into sample values('$id','$name') ",$con))
    {
        $flag['code']=1;
        echo"hi";
    }

    print(json_encode($flag));
    mysql_close($con);
?>

我如何组合1。)和2。)?我试了将近三天,但它根本不起作用,我绝望了:S.希望有人能帮忙。

提前谢谢。

共有1个答案

帅锦
2023-03-14

在同一活动中,首先通过在两个不同的函数中调用这两个代码文件,然后在上载图像文件时,使用子字符串函数从imagepath字符串中获取图像名称,并将该图像名称与JSON数据一起发送到服务器端,同时以ip_地址/image_upload_文件夹/imagename格式插入存储该图像路径。

 类似资料:
  • 我用Android将图像上传到Firebase存储。我有一个应用程序,它可以在抓拍照片后立即发送图像。 但我想创建一个应用程序,在发送前在ImageView中显示照片。我想在照片下面写一些文字,然后把它们都上传。 我应该使用哪些工具来执行此操作?我要从存储器下载毕加索。但我无法管理如何在捕获照片后显示ImageView,然后编写一些文本(如名称或描述)并将其发送给Firebase。第二个挑战是如何

  • 这几天来,我一直对这个问题耿耿于怀,似乎在任何地方都找不到正确的答案。任何帮助都将不胜感激! 最终目标:让用户上传最多4张图片。检查错误。使用文件名上传图片到文件系统中的用户文件夹中(mkdir如果不存在),将文件路径存储在SQL表的相应部分。 我不断地改变事情以获得部分结果,现在我已经把自己编码成了一个大习惯。如果您有任何问题,请告诉我,甚至可以建议一个更好的方法来实现最终目标。 谢谢!! 从框

  • 问题内容: 我要上传图像并将其保存在服务器中。我上传了图像并获得了预览,但是我被困在将图像发送到服务器上。我想使用角度服务将此图像发送到服务器。 这是HTML代码 这是指令 问题答案: 假设您在后端中期望Multipart,这是一段对我有用的代码。 这是一个jsfiddle。 请注意 以下部分: 是一些Angular魔术,为了使$ http解析FormData并找到正确的内容类型,等等。

  • 问题内容: 我想随请求一起发送图像作为参数。我使用下面的代码调用POST请求,但是我不知道如何将图像追加到正文中。 我通过图像选择器获取图像,如下所示: 我的要求如下 我是Swift的新手。我已经通过multipart / form-data看到了这一点,但无法自己实现。我不想将其编码为基本64格式。请帮助我。 问题答案: 我使用以下结构发送图像: 然后在函数中创建如下主体:

  • 我在我的屏幕上有四个图像视图,从相机中捕获图像并显示在其中,现在我想将这些图像上传到服务器上。因此,我使用了下面的代码来获取它们的路径,但它通过了异常。是否有可能从摄像机拍摄的图像视图将图像上传到服务器(无需将图像存储到内存中)。

  • 我从Firebase存储中获取图像,用相机拍照,或者从图书馆中挑选一张。当其中一个完成时,我有一个类来存储,以便在需要时使用它。 现在我需要将此图像上传到Firebase存储(修改或新建,无所谓)。Firebase允许我使用以下选项之一:或,每个选项分别需要或。 我怎么能把我的,并从它获得一个或用于上传? -- 或者,为了解决这个问题,当我从Firebase存储中检索图像时,如何获取图像的? 无论