萌萌噠-上傳

package top.mengmei219.upload;

import android.content.Context;
import android.os.Handler;
import android.os.Message;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.view.View;
import android.widget.EditText;
import android.widget.LinearLayout;
import android.widget.ProgressBar;
import android.widget.Toast;

import java.io.DataInputStream;
import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;
import java.io.OutputStream;
import java.net.HttpURLConnection;
import java.net.MalformedURLException;
import java.net.URL;
import java.net.URLConnection;

import top.mengmei219.upload.util.MimeTypeUtil;

public class MainActivity extends AppCompatActivity implements View.OnClickListener {

    Context mContext;
    LinearLayout ll_progressLayout;
    ProgressBar progress;
    Handler mHandler = new Handler() {
        @Override
        public void handleMessage(Message msg) {
            if(msg.obj!=null && (msg.obj instanceof String)) {
                Toast.makeText(mContext, (String) msg.obj, Toast.LENGTH_SHORT).show();
            }
            //TODO: 這里應(yīng)該加個(gè)動(dòng)畫,慢慢消失
            ll_progressLayout.removeAllViews();
        }
    };


    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);

        mContext = this;

        findViewById(R.id.btn_upload).setOnClickListener(this);
        ll_progressLayout = (LinearLayout) findViewById(R.id.ll_progressLayout);
    }

    @Override
    public void onClick(View v) {
        //加載進(jìn)度條
        progress = (ProgressBar) View.inflate(mContext, R.layout.child_progress, null);
        ll_progressLayout.addView(progress);

        EditText et = (EditText) findViewById(R.id.et_filePath);
        final String filePath = et.getText().toString().trim();

        //開啟子線程上傳
        new Thread(new Runnable() {
            @Override
            public void run() {
                try {
                    URL url = new URL("http://192.168.1.104:8080/itheima74/servlet/UploaderServlet");
                    HttpURLConnection urlConnection = (HttpURLConnection) url.openConnection();
                    urlConnection.setRequestMethod("POST");
                    urlConnection.setConnectTimeout(1000 * 10);

                    //文件上傳請(qǐng)求頭
                    String BOUNDARY = "----WebKitFormBoundarylsvivlBHRlZ8ppnO";
                    urlConnection.setRequestProperty("Content-Type", "multipart/form-data; boundary=" + BOUNDARY);

                    //上傳請(qǐng)求體
                    urlConnection.setDoOutput(true);
                    OutputStream out = urlConnection.getOutputStream();
                    File file = new File(filePath);

                    String filename = file.getName();
                    String mimeType = MimeTypeUtil.getMimeType(file);

                    //請(qǐng)求體(首)
                    StringBuffer sb = new StringBuffer();
                    sb.append("\r\n").append("--").append(BOUNDARY).append("\r\n");
                    sb.append("Content-Disposition: form-data; name=\"" + filePath + "\"; filename=\"" + filename + "\"\r\n");
                    sb.append("Content-Type:" + mimeType + "\r\n\r\n");
                    out.write(sb.toString().getBytes());

                    if (file.exists() && file.isFile()) {
                        //設(shè)置進(jìn)度條總刻度
                        progress.setMax(((int) file.length()));
                        progress.setProgress(0);

                        //請(qǐng)求體(中)
                        FileInputStream in = new FileInputStream(file);
                        byte[] buffer = new byte[1024];
                        int len = 0;
                        while ((len = in.read(buffer)) > 0) {
                            out.write(buffer, 0, len);

                            Thread.sleep(5); //慢觀進(jìn)度條
                            progress.setProgress(progress.getProgress() + len);
                        }
                        in.close();
                    }

                    //請(qǐng)求體(尾)
                    byte[] endData = ("\r\n--" + BOUNDARY + "--\r\n").getBytes();
                    out.write(endData);
                    out.flush();
                    out.close();


                    //處理結(jié)果
                    Message msg = Message.obtain();
                    int code = urlConnection.getResponseCode();
                    if (code == 200) {
                        msg.obj = "上傳成功";
                    } else {
                        msg.obj = "上傳失敗";
                    }
                    mHandler.sendMessage(msg);

                } catch (MalformedURLException e) {
                    e.printStackTrace();
                } catch (IOException e) {
                    e.printStackTrace();
                } catch (InterruptedException e) {
                    e.printStackTrace();
                }
            }
        }).start();

    }
}

最后編輯于
?著作權(quán)歸作者所有,轉(zhuǎn)載或內(nèi)容合作請(qǐng)聯(lián)系作者
【社區(qū)內(nèi)容提示】社區(qū)部分內(nèi)容疑似由AI輔助生成,瀏覽時(shí)請(qǐng)結(jié)合常識(shí)與多方信息審慎甄別。
平臺(tái)聲明:文章內(nèi)容(如有圖片或視頻亦包括在內(nèi))由作者上傳并發(fā)布,文章內(nèi)容僅代表作者本人觀點(diǎn),簡(jiǎn)書系信息發(fā)布平臺(tái),僅提供信息存儲(chǔ)服務(wù)。

相關(guān)閱讀更多精彩內(nèi)容

友情鏈接更多精彩內(nèi)容