简体   繁体   English

使用Android HTTP Post将文件上传到MySQL数据库

[英]Upload Files to MySQL Database using Android HTTP Post

Good day guys please help me, I'm already struggling for more than a month!!! 大家好,请帮我,我已经挣扎了一个多月!!! I want to upload image to MYSQL database and nowhere else. 我想将图像上传到MYSQL数据库,而无其他地方。

What I tried so far: 到目前为止我尝试过的是:

  • Uploading byte array to database=FAIL.(will not upload on server side) 正在将字节数组上传到database = FAIL。(不会在服务器端上传)
  • Connect to mysql database and upload chars as strings=SUCCESS 连接到mysql数据库并以字符串= SUCCESS的形式上传字符
  • Upload bytearray as a string to mysql=FAIL.(again won't upload on server side) 将bytearray作为字符串上传到mysql = FAIL。(同样不会在服务器端上传)

Please give me any full example or even source code how to upload image to mysql database or at least how to upload the link to that image to mysql database and as well as server side PHP code because I don't know php I just need to put in server side by example 请给我任何完整的示例,甚至是源代码,如何将图像上传到mysql数据库,或者至少如何将图像链接上传到mysql数据库以及服务器端PHP代码,因为我不知道php,我只需要以示例方式放在服务器端

Thank you very much beforehand guys, please help me! 非常感谢你们,请帮助我!

Work for me! 为我工作! Method in Class UploadtoServer extends Activiy: 类UploadtoServer中的方法可扩展Activiy:

  public int uploadFile(String sourceFileUri) {

        String lstrArq = SpnListarArquivosCelular.getSelectedItem().toString();
          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()) {

               dialog1.dismiss(); 

               Log.e("uploadFile", "O arquivo não existe :"
                                   +uploadFilePath + "" + lstrArq);

               runOnUiThread(new Runnable() {
                   String lstrArq = SpnListarArquivosCelular.getSelectedItem().toString();
                   public void run() {
                       messageText.setText("O arquivo não existe  :"
                               +uploadFilePath + "" + lstrArq);
                   }
               }); 

               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 lstrArq = SpnListarArquivosCelular.getSelectedItem().toString();
                                String msg = "O arquivo " + lstrArq + " foi enviado com sucesso!";

                                messageText.setText(msg);
                                Toast.makeText(UploadToServer.this, "O arquivo " + lstrArq + " foi enviado com sucesso!", 
                                             Toast.LENGTH_LONG).show();
                            }
                        });                
                   }    

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

              } catch (MalformedURLException ex) {

                  dialog1.dismiss();  
                  ex.printStackTrace();

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

                  Log.e("Erro no servidor", "error: " + ex.getMessage(), ex);  
              } catch (Exception e) {

                  dialog1.dismiss();  
                  e.printStackTrace();

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

           } // End else block 
         } 

Cod PHP in server: 服务器中的Cod PHP:

<?php

    $file_path = "mypatholder/";

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

BYE! BYE!

If you want to upload a picture to server, follow the below code. 如果要将图片上传到服务器,请遵循以下代码。

 public ServerCommunication() {
        HttpParams params = new BasicHttpParams();
        params.setParameter(CoreProtocolPNames.PROTOCOL_VERSION, HttpVersion.HTTP_1_1);
        mHttpClient = new DefaultHttpClient(params);
    }


    public void uploadUserPhoto(File image) {

        try {

            HttpPost httppost = new HttpPost("some url");

            MultipartEntity multipartEntity = new MultipartEntity(HttpMultipartMode.BROWSER_COMPATIBLE);  
            multipartEntity.addPart("xyz", new StringBody("xyz"));
            multipartEntity.addPart("xyz", new StringBody("xyz"));
            multipartEntity.addPart("Image", new FileBody(image));
            httppost.setEntity(multipartEntity);

            mHttpClient.execute(httppost, new PhotoUploadResponseHandler());

        } catch (Exception e) {
            Log.e(ServerCommunication.class.getName(), e.getLocalizedMessage(), e);
        }
    }

    private class PhotoUploadResponseHandler implements ResponseHandler<Object> {

        @Override
        public Object handleResponse(HttpResponse response)
                throws ClientProtocolException, IOException {

            HttpEntity r_entity = response.getEntity();
            String responseString = EntityUtils.toString(r_entity);
            Log.d("UPLOAD", responseString);

            return null;
        }

    }

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM