我如何用排球课升级此代码

时间:2018-06-19 13:15:10

标签: android web-services file-upload android-volley

我使用此代码,并且我知道这是Expired类,并且它也很旧,每个人都可以通过带有进度条的凌空类升级我,以帮助我将文件上传到我的站点,而无需更改服务器端的服务文件!或者,如果您想更改服务的服务器,请说给我看服务器代码!!!预先感谢您的答复!!!

    private class setThumbnailToServer extends AsyncTask<Bitmap, Integer, String> {
        ProgressDialog progressDialog = new ProgressDialog(getContext());
        private long totalSize = 0;


        @Override
        protected void onPreExecute() {
            super.onPreExecute();
            progressDialog.setProgress(0);
            progressDialog.setMax(100);
            progressDialog.setTitle(R.string.dialog_connect_to_server_title);
            progressDialog.setMessage(getString(R.string.dialog_just_moments_content));
            progressDialog.setProgressStyle(ProgressDialog.STYLE_HORIZONTAL);
            progressDialog.setIcon(R.mipmap.ic_launcher);
            progressDialog.show();
        }

        @Override
        protected void onProgressUpdate(Integer... progress) {
            progressDialog.setProgress(progress[0]);
        }

        @Override
        protected String doInBackground(Bitmap... params) {
            try {
                File file = new File(MyApplication.context.getCacheDir(), "/thumbnail.jpeg");
                if (file.exists()) {
                    Log.e(MyApplication.LOG_TAG, "file exited");
                    if (file.delete()) {
                        Log.e(MyApplication.LOG_TAG, "file not exited");
                        file.createNewFile();
                        FileOutputStream fileOutputStream;
                        Bitmap bitmap = params[0];
                        ByteArrayOutputStream byteArrayOutputStream = new ByteArrayOutputStream();
                        bitmap.compress(Bitmap.CompressFormat.JPEG, 100, byteArrayOutputStream);
                        byte[] bytes = byteArrayOutputStream.toByteArray();
                        fileOutputStream = new FileOutputStream(file);
                        fileOutputStream.write(bytes);
                        fileOutputStream.flush();
                        fileOutputStream.close();
                        Log.e(MyApplication.LOG_TAG, "file created");
                    }
                } else {
                    Log.e(MyApplication.LOG_TAG, "file not exited");
                    file.createNewFile();
                    FileOutputStream fileOutputStream;
                    Bitmap bitmap = params[0];
                    ByteArrayOutputStream byteArrayOutputStream = new ByteArrayOutputStream();
                    bitmap.compress(Bitmap.CompressFormat.JPEG, 100, byteArrayOutputStream);
                    byte[] bytes = byteArrayOutputStream.toByteArray();
                    fileOutputStream = new FileOutputStream(file);
                    fileOutputStream.write(bytes);
                    fileOutputStream.flush();
                    fileOutputStream.close();
                    Log.e(MyApplication.LOG_TAG, "file created again");
                }
            } catch (IOException ex) {
                Log.e(MyApplication.LOG_TAG, "Error is in the Upload Thumbnail" + ex.getMessage());
            }
            if (new File(MyApplication.context.getCacheDir().getAbsolutePath() + "/thumbnail.jpeg").exists()) {
                return uploadFile(person.getID(), person.getThumbnailURL(), MyApplication.context.getCacheDir().getAbsolutePath() + "/thumbnail.jpeg");
            } else {
                return null;
            }
        }

        @SuppressWarnings("deprecation")
        private String uploadFile(String ID, String ThumbnailURL, String ThumbnailPath) {
            String responseString = null;

            HttpClient httpclient = new DefaultHttpClient();
            HttpPost httppost = new HttpPost(WebService.setThumbnail());

            try {
                AndroidMultiPartEntity androidMultiPartEntity = new AndroidMultiPartEntity(
                        new AndroidMultiPartEntity.ProgressListener() {
                            @Override
                            public void transferred(long num) {
                                publishProgress((int) ((num / (float) totalSize) * 100));
                            }
                        });

                File file = new File(ThumbnailPath);

                // Adding file data to http body
                androidMultiPartEntity.addPart("Content", new FileBody(file));

                // Extra parameters if you want to pass to server
                androidMultiPartEntity.addPart("ID", new StringBody(ID));
                androidMultiPartEntity.addPart("ThumbnailURL", new StringBody(ThumbnailURL));

                totalSize = androidMultiPartEntity.getContentLength();
                httppost.setEntity(androidMultiPartEntity);

                // Making server call
                HttpResponse httpResponse = httpclient.execute(httppost);
                HttpEntity httpEntity = httpResponse.getEntity();

                int statusCode = httpResponse.getStatusLine().getStatusCode();
                if (statusCode == 200) {
                    responseString = EntityUtils.toString(httpEntity);
                    progressDialog.dismiss();
                } else {
                    responseString = "Error occurred! Http Status Code: " + statusCode;
                    progressDialog.dismiss();
                    SyncServer.showNoInternetDialog(getContext());
                }

            } catch (IOException e) {
                responseString = e.toString();
                progressDialog.dismiss();
            }
            return responseString;
        }

        @Override
        protected void onPostExecute(String Response) {
            super.onPostExecute(Response);
            materialDialog.show();
            Log.e(MyApplication.LOG_TAG, "Response:" + Response);
            try {
                JSONObject jsonObject = new JSONObject(Response);
                boolean Error = jsonObject.getBoolean("error");
                if (Error) {
                    int ErrorCode = jsonObject.getInt("error-code");
                    String Message = jsonObject.getString("message");
                    Log.e(MyApplication.LOG_TAG, "ErrorCode=" + ErrorCode + ",Message:" + Message);
                    if (ErrorCode == 13) {
                        JSONObject jsonPerson = jsonObject.getJSONObject("person");
                        Log.i(MyApplication.LOG_TAG, "Person:" + jsonPerson.toString());
                        PersonClass Person = WebService.personParser(jsonPerson);
                        if (Database.updatePerson(Person)) {
                            showDialogNotSetThumbnail(Person);
                        }

                    }
                } else {
                    int Code = jsonObject.getInt("code");
                    String Message = jsonObject.getString("message");
                    String FullThumbnailURL = jsonObject.getString("Full-Thumbnail-URL");
                    String ThumbnailURL = jsonObject.getString("Thumbnail-URL");
                    Log.i(MyApplication.LOG_TAG, "Message from web service:" + Message);
                    Log.i(MyApplication.LOG_TAG, "ThumbnailURL : " + ThumbnailURL);
                    Log.i(MyApplication.LOG_TAG, "Full Thumbnail URL : " + FullThumbnailURL);
                    if (Code == 2) {
                        picture.setID(person.getID());
                        if (Database.setPicture(picture)) {
                            showActivateActivity(person.getID());
                        }
                    }
                }
            } catch (JSONException e) {
                showDialogNotSetThumbnail(person);
                Log.e(MyApplication.LOG_TAG, "json parsing error: " + e.getMessage());
            }

            // showing the server response in an alert dialog
        }
    }

    @SuppressWarnings("deprecation")
public class AndroidMultiPartEntity extends MultipartEntity

{

    private final ProgressListener progressListener;

    public AndroidMultiPartEntity(final ProgressListener progressListener) {
        super();
        this.progressListener = progressListener;
    }

    public AndroidMultiPartEntity(final HttpMultipartMode mode,
                                  final ProgressListener listener) {
        super(mode);
        this.progressListener = listener;
    }

    public AndroidMultiPartEntity(HttpMultipartMode mode, final String boundary, final Charset charset, final ProgressListener listener) {
        super(mode, boundary, charset);
        this.progressListener = listener;
    }

    @Override
    public void writeTo(final OutputStream outputStream) throws IOException {
        super.writeTo(new CountingOutputStream(outputStream, this.progressListener));
    }

    public static interface ProgressListener {
        void transferred(long num);
    }

    public static class CountingOutputStream extends FilterOutputStream {

        private final ProgressListener listener;
        private long transferred;

        public CountingOutputStream(final OutputStream out,
                                    final ProgressListener listener) {
            super(out);
            this.listener = listener;
            this.transferred = 0;
        }

        public void write(byte[] b, int off, int len) throws IOException {
            out.write(b, off, len);
            this.transferred += len;
            this.listener.transferred(this.transferred);
        }

        public void write(int b) throws IOException {
            out.write(b);
            this.transferred++;
            this.listener.transferred(this.transferred);
        }
    }
}

这是我在服务器端的代码:

    function setThumbnail($ID, $ThumbnailURL)
{
    $response = array();
    $PolicyState = getPolicySetThumbnail($ID);
    if ($PolicyState == 2) {
        $DIR = 'thumbnails/' . $ThumbnailURL . '/';
        $Message = "";
        if (!file_exists($DIR)) {
            mkdir($DIR, 0777, true);
            $Message = $DIR . " Created.";
        }
        $ThumbnailFile = $DIR . basename($_FILES['Content']['name']);
        try {
            if (move_uploaded_file($_FILES['Content']['tmp_name'], $ThumbnailFile)) {
                $response["error"] = false;
                $response["code"] = 2;
                $response["message"] = $Message . "The file " . basename($_FILES['Content']['name']) . " has been uploaded";
                $response["Full-Thumbnail-URL"] = "http://example.com/" . $ThumbnailFile;
                $response["Thumbnail-URL"] = $ThumbnailFile;
            } else {
                throw new Exception('Could not move file');
            }
        } catch (Exception $ex) {
            if (setThumbnailDefault($ID) == 1) {
                $response["person"] = getPersonRecordWithoutInquiry($ID);
                $response["error"] = true;
                $response["error-code"] = 13;
                $response["message"] = $ex->getMessage();
            }
        }
    } else if ($PolicyState == 1) {
        $response["error"] = false;
        $response["code"] = 1;
        $response["message"] = "This ID couldn't set his thumbnail because Thumbnail is Default";
    } else if ($PolicyState == 3) {
        $response["error"] = true;
        $response["error-code"] = 1;
        $response["message"] = "This ID is not exists";
    } else if ($PolicyState == 0) {
        $response["error"] = true;
        $response["error-code"] = 4096;
        $response["message"] = "server error or connection or binding";
    }
    echo json_encode($response);
}

0 个答案:

没有答案