簡體   English   中英

問題-將圖像上傳到Android中的服務器

[英]Issue - Uploading images to server in Android

嗨,我需要將圖像從SD卡上傳到服務器,以下是我在課堂上使用的代碼,我無法將圖像從SD卡發送到服務器,而且我也沒有從服務器獲得任何響應上傳成功與否。 誰能幫我嗎 ? 我已經嘗試了很多次,但我不知道下面的代碼在哪里出現問題。 同樣,請檢查我下面給出的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
    }
}`

這是我正在使用的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";
   }
}

在您的PHP代碼中,您正在檢查ID android,但我找不到任何conn.setRequestProperty()將值設置為“ android”,請嘗試添加一些具有值“ android”的屬性

如果未成功,請嘗試以下代碼來上傳文件,我正在應用程序中使用此代碼將圖像上傳到服務器。

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();
    }

試試這個代碼

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;
}

這段代碼是用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);

和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