简体   繁体   English

问题-将图像上传到Android中的服务器

[英]Issue - Uploading images to server in Android

HI I need to upload images from SD card to server, the following code i am using in my class, i can't able to send images from my SD card to the server and also i didn't get any response from server whether it is uploading successfully or not. 嗨,我需要将图像从SD卡上传到服务器,以下是我在课堂上使用的代码,我无法将图像从SD卡发送到服务器,而且我也没有从服务器获得任何响应上传成功与否。 Can anyone help me out ? 谁能帮我吗 ? I have tried many times, i dont know where i am getting problem in my below code. 我已经尝试了很多次,但我不知道下面的代码在哪里出现问题。 As well please check my below PHP Script which i have given, is it right or wrong. 同样,请检查我下面给出的PHP脚本,对还是错。

  public class UploadImage {

    static int serverResponseCode = 0;

    /********** File Path *************/
    final static String uploadFilePath =         Environment.getExternalStorageDirectory().getPath() + "/PMGRMS/";
    static String upLoadServerUri = "api-filepath";

    public static int uploadImage(String fName) {

        String fileName = uploadFilePath + "service_lifecycle.png";

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

        if (!sourceFile.isFile()) {

            Log.e("UploadImage: ", "Image not found on SD");

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

                // 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) {
                    Log.i("UploadImage: ", "Image not found on SD");
                }

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

            } catch (MalformedURLException ex) {

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

                Log.e("Upload file to server Exception", "Exception : " + e.getMessage(), e);
            }
            return serverResponseCode;

        } // End else block
    }
}`

here is my php script that i am using.. 这是我正在使用的PHP脚本。

// PHP Script

     if($id == "android")
{
  // gallery path  
    $file_path = "../Gallery/Android/";
 $file_path = $file_path . basename( $_FILES['PMGRMS']['name']);
   if(move_uploaded_file($_FILES['PMGRMS']['tmp_name'], $file_path)) {
       echo "Image is upload";
   } else{enter code here
       echo "Image is not Upload";
   }
}

in your php code you are checking for the id android but i could not find any conn.setRequestProperty() setting a value to "android" please try adding some property that has a value "android" 在您的PHP代码中,您正在检查ID android,但我找不到任何conn.setRequestProperty()将值设置为“ android”,请尝试添加一些具有值“ android”的属性

if not success please try the below code for uploading your files, i'm using this in my application to upload images to my server. 如果未成功,请尝试以下代码来上传文件,我正在应用程序中使用此代码将图像上传到服务器。

public String multipartRequest(String urlTo, String post, String filepath, String filefield) throws ParseException, IOException {

        HttpURLConnection connection = null;
        DataOutputStream outputStream = null;
        InputStream inputStream = null;

        String twoHyphens = "--";
        String boundary = "*****" + Long.toString(System.currentTimeMillis()) + "*****";
        String lineEnd = "\r\n";

        String result = "";

        int bytesRead, bytesAvailable, bufferSize;
        byte[] buffer;
        int maxBufferSize = 1 * 1024 * 1024;

        String[] q = filepath.split("/");
        int idx = q.length - 1;

        try {
            File file = new File(filepath);
            FileInputStream fileInputStream = new FileInputStream(file);

            URL url = new URL(urlTo);
            connection = (HttpURLConnection) url.openConnection();

            connection.setDoInput(true);
            connection.setDoOutput(true);
            connection.setUseCaches(false);

            connection.setRequestMethod("POST");
            connection.setRequestProperty("Connection", "Keep-Alive");
            connection.setRequestProperty("User-Agent", "Android Multipart HTTP Client 1.0");
            connection.setRequestProperty("Content-Type", "multipart/form-data; boundary=" + boundary);

            outputStream = new DataOutputStream(connection.getOutputStream());
            outputStream.writeBytes(twoHyphens + boundary + lineEnd);
            outputStream.writeBytes("Content-Disposition: form-data; name=\"" + filefield + "\"; filename=\"" + q[idx] + "\"" + lineEnd);
            outputStream.writeBytes("Content-Type: application/octet-stream" + lineEnd);
            outputStream.writeBytes("Content-Type: image/jpeg" + lineEnd);
            outputStream.writeBytes("Content-Transfer-Encoding: binary" + lineEnd);
            outputStream.writeBytes(lineEnd);

            bytesAvailable = fileInputStream.available();
            bufferSize = Math.min(bytesAvailable, maxBufferSize);
            buffer = new byte[bufferSize];
            final double totalSize = bytesAvailable;

            bytesRead = fileInputStream.read(buffer, 0, bufferSize);
            double uploaded = bytesRead;
            while (bytesRead > 0) {
                outputStream.write(buffer, 0, bufferSize);
                bytesAvailable = fileInputStream.available();
                final int percent = (int) (uploaded / totalSize) * 100;
                final double sizeUploaded = uploaded;
                mContext.runOnUiThread(new Runnable() {
                    @Override
                    public void run() {
                        upload_progress.setProgress(percent);
                        title.setText(sizeUploaded + "(" + totalSize + ")");
                    }
                });
                System.out.println(uploaded / totalSize);
                bufferSize = Math.min(bytesAvailable, maxBufferSize);
                bytesRead = fileInputStream.read(buffer, 0, bufferSize);
                uploaded = uploaded + bytesRead;
                HomeActivity.mNotifyBuilder.setProgress(100, percent, false);
                // Displays the progress bar for the first time.
                HomeActivity.mNotificationManager.notify(HomeActivity.NOTIFICATION_ID, HomeActivity.mNotifyBuilder.build());
            }

            outputStream.writeBytes(lineEnd);

            // Upload POST Data
            String[] posts = post.split("&");
            int max = posts.length;
            for (int i = 0; i < max; i++) {
                outputStream.writeBytes(twoHyphens + boundary + lineEnd);
                String[] kv = posts[i].split("=");
                outputStream.writeBytes("Content-Disposition: form-data; name=\"" + kv[0] + "\"" + lineEnd);
                outputStream.writeBytes("Content-Type: text/plain" + lineEnd);
                outputStream.writeBytes(lineEnd);
                outputStream.writeBytes(kv[1]);
                outputStream.writeBytes(lineEnd);
            }

            outputStream.writeBytes(twoHyphens + boundary + twoHyphens + lineEnd);

            inputStream = connection.getInputStream();
            result = this.convertStreamToString(inputStream);

            fileInputStream.close();
            inputStream.close();
            outputStream.flush();   
            outputStream.close();

            return result;
        } catch (Exception e) {
            Log.e("MultipartRequest", "Multipart Form Upload Error");
            e.printStackTrace();
            return "error";
        }
    }

    private String convertStreamToString(InputStream is) {
        BufferedReader reader = new BufferedReader(new InputStreamReader(is));
        StringBuilder sb = new StringBuilder();

        String line = null;
        try {
            while ((line = reader.readLine()) != null) {
                sb.append(line);
            }
        } catch (IOException e) {
            e.printStackTrace();
        } finally {
            try {
                is.close();
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
        return sb.toString();
    }

try this code 试试这个代码

public String postData(String post_url,List<NameValuePair> post_parameters_list,String file) throws ClientProtocolException, IOException
{
        int response_code = -1;
        HttpPost httppost = new HttpPost(post_url);
        httppost.setEntity(new UrlEncodedFormEntity(post_parameters_list));
        FileEntity reqEntity = new FileEntity(new File(file),"binary/octet-stream");
        reqEntity.setChunked(true);
        httppost.setEntity(reqEntity);
        HttpResponse response = httpclient.execute(httppost);
        response_code = response.getStatusLine().getStatusCode();
        if (response_code == HttpStatus.SC_UNAUTHORIZED)
        {
            Log.e("HttpResponse", "un authorized");
    //      insertActivityLog("Session timed out. The operation will be retried again");
        }
        else if(response_code == 999 || response_code == HttpStatus.SC_INTERNAL_SERVER_ERROR)
        {
            Log.e("HttpResponse", "Internal Server");
            new Error("Time Out","Internal Server Error. Please contact support.");
        }
        else if(response_code == -1 )
        {
            Log.e("HttpResponse", "Socket connection timeout");
            new Error("Time Out","Response returned from the server is empty. Please contact support.");
        }
        if (response_code == HttpStatus.SC_UNAUTHORIZED)
        {
            // credential check failed
            Log.e("HTTP status", "unauthorised");
            new Error("UNAUTHORIZED","unauthorised for the user " + post_parameters_list.get(0).getName());
        }
        else if (response_code == HttpStatus.SC_FORBIDDEN)
        {
            // forbidden
            Log.e("HTTP status", "Forbidden");
            new Error("Forbidden","User " + post_parameters_list.get(0).getName() + " does not have access to this project");
        }
        return response_code == HttpStatus.SC_OK ? EntityUtils.toString(response.getEntity()) : null;
}

This code is work use java 这段代码是用java工作的

HttpClient client = new DefaultHttpClient();
HttpPost postMethod = new HttpPost("http://192.195.68.83/Upload/index.php");
File file = new File(fileUri.getPath());
MultipartEntity entity = new MultipartEntity();
FileBody contentFile = new FileBody(file);
entity.addPart("userfile",contentFile);
StringBody contentString = new StringBody("This is contentString");
entity.addPart("contentString",contentString);

postMethod.setEntity(entity);
HttpResponse response = client.execute(postMethod);

and php's code 和PHP的代码

$uploads_dir = '/Library/WebServer/Documents/Upload/upload/'.$_FILES['userfile']['name'];
if(is_uploaded_file($_FILES['userfile']['tmp_name'])) {
        echo $_POST["contentString"]."\n";
        echo  "File path = ".$uploads_dir;
        move_uploaded_file ($_FILES['userfile'] ['tmp_name'], $uploads_dir);
} else {
        echo "\n Upload Error";
        echo "filename '". $_FILES['userfile']['tmp_name'] . "'.";
        print_r($_FILES);
}

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

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