使用php+android+wamp将图像和文本信息上传到mysql-db



我成功地将图像直接上传到服务器文件夹,但我想将sme文本信息和图片一起存储到数据库中,并将图像存储在服务器中,路径存储在数据库中。。?

使用此代码。。。

字符串fileName=sourceFileUri;

    HttpURLConnection conn = null;
    DataOutputStream dos = null; 
    String lineEnd = "rn";
    String twoHyphens = "--";
    String boundary = "*****";
    int bytesRead, bytesAvailable, bufferSize;
    byte[] buffer;
    int maxBufferSize = 1 * 1024 * 1024;
    File sourceFile = new File(sourceFileUri);
    if (!sourceFile.isFile()) {
        dialog = ProgressDialog.show(CameraPhotoCapture.this, "", "Uploading file...", true);
        dialog.dismiss();
        Log.e("uploadFile", "Source File not exist :" );
        runOnUiThread(new Runnable() {
            public void run() {
                //   messageText.setText("Source File not exist :"                             +uploadFilePath + "" + uploadFileName);
            }
        });
        return 0;
    }
    else
    {
        try {
            // open a URL connection to the Servlet
            FileInputStream fileInputStream = new FileInputStream(sourceFile);
            URL url = new URL(upLoadServerUri);


            conn = (HttpURLConnection) url.openConnection();
            conn.setDoInput(true); 
            conn.setDoOutput(true);
            conn.setUseCaches(false); 
            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() {

                        File se = new File(full_path_name);
                        String ser = se.getName();
                        String string =full_path_name;
                        String[] parts = string.split("/");
                        String part1 = parts[0]; // 004
                        String part2 = parts[1]; 
                        String part3 = parts[2];
                        String part4 = parts[3];
                        String msg = "http://172.17.2.139/manimca/smartcomplaints/images/"+part4;

                        //    messageText.setText(msg);
                        Toast.makeText(CameraPhotoCapture.this, "File Upload Complete.",
                                Toast.LENGTH_SHORT).show();



                        ArrayList<NameValuePair> nameValuePairs = new ArrayList<NameValuePair>();
                        nameValuePairs.add(new BasicNameValuePair("complaint_type", $complaint_type));
                        nameValuePairs.add(new BasicNameValuePair("complaint_details", $complaint_details));
                        nameValuePairs.add(new BasicNameValuePair("image_details", $image_details));
                        nameValuePairs.add(new BasicNameValuePair("latitude",$latitude));
                        nameValuePairs.add(new BasicNameValuePair("longitude", $longitude));
                        nameValuePairs.add(new BasicNameValuePair("area", $area));
                        nameValuePairs.add(new  BasicNameValuePair("datetime", myDate));
                        nameValuePairs.add(new  BasicNameValuePair("people_name", $people_name));
                        nameValuePairs.add(new  BasicNameValuePair("people_email", $people_email));
                        nameValuePairs.add(new  BasicNameValuePair("people_address", $people_address));
                        nameValuePairs.add(new  BasicNameValuePair("phoneno", $phoneno));

                        try
                        {
                            HttpClient httpclient = new DefaultHttpClient();
                            HttpPost httppost = new HttpPost("http://172.17.2.139/manimca/smartcomplaints/complaint_informations.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());
                        }
                    }
                });               
            }   
            //close the streams //
            fileInputStream.close();
            dos.flush();
            dos.close();
            finish();
        } catch (MalformedURLException ex) {
            dialog.dismiss(); 
            ex.printStackTrace();
            runOnUiThread(new Runnable() {
                public void run() {
                    //      messageText.setText("MalformedURLException Exception : check script url.");
                    Toast.makeText(CameraPhotoCapture.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(CameraPhotoCapture.this, "No Internet Connection ",
                            Toast.LENGTH_SHORT).show();
                }
            });
            Log.e("Upload file to server Exception", "Exception : "
                    + e.getMessage(), e); 
        }
        dialog.dismiss();      
        return serverResponseCode;
    } // End else block
}

public void showMessgeAlert(String Message)
{
    Toast.makeText(getApplicationContext(), Message, Toast.LENGTH_SHORT).show();
}

我不能完全理解您的问题,但我认为您希望将有关文件的一些数据保存到数据库中。如果这确实是你的问题,请继续阅读。

将上传的文件从其原始文件名重命名始终是一种很好的做法。使用哈希创建一个新的文件名,并将文件(在本例中为图像)保存到webroot中的上传文件夹中。然后在数据库中插入一条记录,其中包含应用程序所需的所有信息。这样就不必像文件大小或mime类型那样查询文件系统。还要将原始文件名保存在记录中,包括一些关于图像的文本(我想这就是你想要做的)。我不会详细介绍代码,因为PHP有很多例子。

最新更新