Httpurlconction 向Servlet 传大文件

Httpurlconction 与Servlet 之间相互传参

———-Httpurl:———-

public static void uploadFile(final Context context) {

        new AsyncTask<String, Long, String>() {

            protected void onPreExecute() {

                View view = LayoutInflater.from(context).inflate(R.layout.dialog_upload_db_progress, null);
                progressbar = (ProgressBar) view.findViewById(R.id.progressBar);
                tv_uploadState = (TextView) view.findViewById(R.id.uploadState);
                tv_uploadProgress = (TextView) view.findViewById(R.id.uploadProgress);
                dialog = new Dialog(context, R.style.loadDialog);
                dialog.setContentView(view);
                dialog.setCancelable(false);

                // 设置dialog的尺寸
                WindowManager.LayoutParams params = dialog.getWindow().getAttributes();
                DisplayMetrics displayMetrics = context.getResources().getDisplayMetrics();
                int screenWidth = displayMetrics.widthPixels;
                int screenHeight = displayMetrics.heightPixels;
                params.width = screenWidth / 5 * 4;
                params.height = screenHeight / 5;
                dialog.getWindow().setAttributes(params);

                // 设置progress初始的进度值
                progressbar.setProgress(0);
                progressbar.setMax(100);
                tv_uploadState.setText("正在上传......");
                tv_uploadProgress.setText("0%");

                dialog.show();

            };

            @Override
            protected String doInBackground(String... params) {

                // 获得PAd 店员的信息和电源的id
                mUserDao = DaoManager.getDao(UserDao.class, context);
                User user;
                String nickName = null;
                long userId = 0;

                try {
                    user = mUserDao.getData();
                    nickName = user.getNickName();
                    userId = user.getId();

                } catch (SQLException e1) {
                    e1.printStackTrace();
                }

                File file = new File(FILE_NAME);
                length = file.length();

                FileInputStream fis = null;
                OutputStream os = null;
                HttpURLConnection connection = null;
                InputStream inputStream = null;
                ByteArrayOutputStream baos = null;

                try {
                    URL url = new URL(urlString);
                    fis = new FileInputStream(file);

                    byte[] buff = new byte[1024];
                    int len = 0;
                    long startPosition = 0L;
                    int times = 0;
                    long progress = 0L;

                    while ((len = fis.read(buff)) != -1) {

                        // byte[] b = Arrays.copyOfRange(buff, 0, len);
                        // uploadToServlet(startPosition, b);
                        // startPosition += len;

                        if (times == 0) {
                            connection = (HttpURLConnection) url.openConnection();
                            connection.setDoOutput(true);
                            connection.setDoInput(true);
                            connection.setRequestMethod("POST");
                            connection.setUseCaches(false);
                            connection.setRequestProperty("startPosition", String.valueOf(startPosition));
                            connection.setRequestProperty("fileName", nickName + "_" + userId + "_" + PhoneUtil.getVersionName(context));
                            // connection.connect();
                            connection.setConnectTimeout(30000);
                            connection.setReadTimeout(60000 * 3);
                            os = connection.getOutputStream();
                        }
                        times++;
                        os.write(buff);
                        os.flush();

                        progress += len;

                        if (times == 1024 * 1 || progress == length) {// 每次长传1M
                            times = 0;
                            os.close();
                            if (connection.getResponseCode() == 200) {

                                // 获得服务端发来的响应
                                inputStream = connection.getInputStream();
                                baos = new ByteArrayOutputStream();

                                byte[] bMessage = new byte[1024];
                                int m = 0;
                                while ((m = inputStream.read(bMessage)) != -1) {
                                    baos.write(bMessage, 0, m);
                                }

                                String message = new String(baos.toByteArray());

                                Log.i("AAAA", "==message:" + message);

                                inputStream.close();
                                baos.close();

                                if ("successful".equals(message)) {
                                    publishProgress(progress);
                                } else {
                                    // TODO:上传失败
                                    uploadAgainDialog("上传失败,是否重新上传", context);
                                    break;
                                }

                            }
                        }

                        startPosition += len;

                    }

                    fis.close();

                } catch (IOException e) {

                    Log.i("AAAA", "=IOException=" + e.toString());
                    uploadAgainDialog("网络异常,上传失败,是否重新上传", context);
                    e.printStackTrace();

                } finally {

                    try {
                        if (fis != null) {
                            fis.close();
                        }

                        if (os != null) {
                            os.close();
                        }
                        if (baos != null) {
                            baos.close();
                        }
                        if (inputStream != null) {
                            inputStream.close();
                        }

                    } catch (IOException e) {
                        // TODO Auto-generated catch block
                        e.printStackTrace();
                    }

                }

                return null;
            }

            protected void onProgressUpdate(Long... values) {

                progressbar.setProgress((int) (values[0] * 100 / length));
                tv_uploadProgress.setText((int) (values[0] * 100 / length) + "%");

                if (values[0] == length) {
                    tv_uploadState.setText("上传完成");

                }

            }

            protected void onPostExecute(String result) {
                dialog.dismiss();

            };

        }.execute("");

    }

    public static void uploadAgainDialog(final String title, final Context context) {

        ((Activity) context).runOnUiThread(new Runnable() {

            @Override
            public void run() {
                View view = LayoutInflater.from(context).inflate(R.layout.dialog_upload_db, null);
                Button btn_sure = (Button) view.findViewById(R.id.btn_sure_upload);
                Button btn_cancle = (Button) view.findViewById(R.id.btn_cancle_upload);
                TextView tv_title = (TextView) view.findViewById(R.id.dialogTitle);
                tv_title.setText(title);

                final Dialog dialog = new Dialog(context, R.style.loadDialog);
                dialog.setContentView(view);

                WindowManager.LayoutParams params = dialog.getWindow().getAttributes();

                DisplayMetrics displayMetrics = context.getResources().getDisplayMetrics();
                int screenWidth = displayMetrics.widthPixels;
                int screenHeight = displayMetrics.heightPixels;

                params.width = screenWidth / 5 * 4;
                params.height = screenHeight / 5;

                dialog.getWindow().setAttributes(params);

                btn_cancle.setOnClickListener(new OnClickListener() {

                    @Override
                    public void onClick(View v) {

                        dialog.dismiss();

                    }
                });

                btn_sure.setOnClickListener(new OnClickListener() {

                    public void onClick(View v) {
                        BigFileUploadUtil.uploadFile(context);
                        dialog.dismiss();

                    }
                });

                dialog.show();

            }
        });

    }

———-## Servlet端 ##———-

public class MyServlet extends HttpServlet {

    protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
    }

    protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        getDataOfBigFile(request, response);
    }

    private void getDataOfBigFile(HttpServletRequest request, HttpServletResponse response) {

        String fileName = request.getHeader("fileName");
        String startPosition = request.getHeader("startPosition");
        long mStartWrite = Long.parseLong(startPosition);
        System.out.println(mStartWrite);
        InputStream is = null;
        RandomAccessFile mAccessFile = null;
        PrintWriter pw = null;

        try {
            is = request.getInputStream();
            File file = new File("F:/" + fileName);

            // System.out.println(is.available());
            byte[] b = new byte[1024 * 8];
            int len = 0;

            if (mStartWrite == 0L) {// 每次重新上传数据时,将文件的清空
                if (file.exists()) {
                    file.delete();
                    System.out.println("delete");
                }

            }

            mAccessFile = new RandomAccessFile(file, "rw");
            mAccessFile.seek(mStartWrite);

            while ((len = is.read(b)) > 0) {
                // System.out.println(len);
                mAccessFile.write(b, 0, len);
            }

            pw = response.getWriter();
            pw.write("successful");
            pw.flush();

        } catch (Exception e) {
            PrintWriter pw1 = null;
            try {

                pw1 = response.getWriter();
                pw1.write("failure");
                pw1.flush();
                pw1.close();
            } catch (IOException e1) {
                e1.printStackTrace();
            } finally {
                if (pw1 != null) {
                    pw1.close();
                }

            }

            e.printStackTrace();

        } finally {
            try {
                if (is != null) {
                    is.close();
                }

                if (mAccessFile != null) {
                    mAccessFile.close();

                }
                if (pw != null) {
                    pw.close();
                }

            } catch (IOException e) {
                e.printStackTrace();
            }

        }

        // System.out.println(startPosition + "完毕");

    }
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
经导师精心指导并认可、获 98 分的毕业设计项目!【项目资源】:微信小程序。【项目说明】:聚焦计算机相关专业毕设及实战操练,可作课程设计与期末大作业,含全部源码,能直用于毕设,经严格调试,运行有保障!【项目服务】:有任何使用上的问题,欢迎随时与博主沟通,博主会及时解答。 经导师精心指导并认可、获 98 分的毕业设计项目!【项目资源】:微信小程序。【项目说明】:聚焦计算机相关专业毕设及实战操练,可作课程设计与期末大作业,含全部源码,能直用于毕设,经严格调试,运行有保障!【项目服务】:有任何使用上的问题,欢迎随时与博主沟通,博主会及时解答。 经导师精心指导并认可、获 98 分的毕业设计项目!【项目资源】:微信小程序。【项目说明】:聚焦计算机相关专业毕设及实战操练,可作课程设计与期末大作业,含全部源码,能直用于毕设,经严格调试,运行有保障!【项目服务】:有任何使用上的问题,欢迎随时与博主沟通,博主会及时解答。 经导师精心指导并认可、获 98 分的毕业设计项目!【项目资源】:微信小程序。【项目说明】:聚焦计算机相关专业毕设及实战操练,可作课程设计与期末大作业,含全部源码,能直用于毕设,经严格调试,运行有保障!【项目服务】:有任何使用上的问题,欢迎随时与博主沟通,博主会及时解答。
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值