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

时间:2014-01-02 08:33:49

标签: php 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";
   }
}

3 个答案:

答案 0 :(得分:0)

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

答案 1 :(得分:0)

试试这段代码

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

答案 2 :(得分:0)

这段代码是工作用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);
}