上传文件简易操作

第一步:

		****需要将文件放入模拟器中的文件管理中****

第2步:读写权限

	 <uses-permission android:name="android.permission.READ_EXTERNAL_STORAGE" />
	   <uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE" />
	   <uses-permission android:name="android.permission.INTERNET" />

第三步:获得文件

这是上传位置的接口
http://yun918.cn/study/public/file_upload.php

		final HashMap<String, String> params = new HashMap<>();
            params.put("key", "1909A");
            String path = Environment.getExternalStorageDirectory()+File.separator+"abc.jpg";
            file1 = new File(path);

然后需要将上传文件的方法放入线程中,其中参数是第三步获得的对象

		 new Thread(new Runnable() {
                @Override
                public void run() {
                    try {
                        initOkUpload(params,"file", file1, file1.getName(),url);
                    } catch (Exception e) {
                        e.printStackTrace();
                    }
                }
            }).start();

第4步:

 private static final String TAG = "MainActivity";
private void initOkUpload(HashMap<String, String> params, String fileFormName, File uploadFile,
                          String newFileName, String urlStr) throws IOException {
    if (newFileName == null || newFileName.trim().equals("")) {
        newFileName = uploadFile.getName();
    }

    StringBuilder sb = new StringBuilder();

    if (params != null) {
        for (String key : params.keySet()) {
            sb.append("--" + BOUNDARY + "\r\n");
            sb.append("Content-Disposition: form-data; name=\"" + key + "\"" + "\r\n");
            sb.append("\r\n");
            sb.append(params.get(key) + "\r\n");
        }
    }

第5步:上传文件的头

/**
* 上传文件的头
*/
sb.append("–" + BOUNDARY + “\r\n”);
sb.append(“Content-Disposition: form-data; name=”" + fileFormName + “”; filename="" + newFileName + “”"
+ “\r\n”);
sb.append(“Content-Type: application/octet-stream” + “\r\n”);// 如果服务器端有文件类型的校验,必须明确指定ContentType
sb.append("\r\n");

    byte[] headerInfo = sb.toString().getBytes("UTF-8");
    byte[] endInfo = ("\r\n--" + BOUNDARY + "--\r\n").getBytes("UTF-8");

第6步:进行文件传输,上传

    URL url = new URL(urlStr);
    HttpURLConnection conn = (HttpURLConnection) url.openConnection();
    conn.setRequestMethod("POST");
    // 设置传输内容的格式,以及长度
    conn.setRequestProperty("Content-Type", "multipart/form-data; boundary=" + BOUNDARY);
    conn.setRequestProperty("Content-Length",
            String.valueOf(headerInfo.length + uploadFile.length() + endInfo.length));
    conn.setDoOutput(true);

    OutputStream out = conn.getOutputStream();
    InputStream in = new FileInputStream(uploadFile);

第七步:写入文件长度和给progress配置

    //写入的文件长度
    int count = 0;
    //文件的总长度
    int available = in.available();
    // 写入头部 (包含了普通的参数,以及文件的标示等)
    out.write(headerInfo);
    // 写入文件
    byte[] buf = new byte[1024];
    int len;
    while ((len = in.read(buf)) != -1) {
        out.write(buf, 0, len);
        count += len;
        int progress1 = count * 100 / available;
        Log.d(TAG, "上传进度: " + progress1 + " %");
    progress.setProgress(progress1);
    }

## 第8: 写入尾部
// 写入尾部
out.write(endInfo);
in.close();
out.close();
if (conn.getResponseCode() == 200) {
System.out.println(“文件上传成功”);
String s = stream2String(conn.getInputStream());
Log.d(TAG, "uploadForm: " + s);
}

第9步:这是分割符,自定义的也就是stream2String

// 分割符,自己定义即可
private static final String BOUNDARY = “----WebKitFormBoundaryT1HoybnYeFOGFlBR”;

public String stream2String(InputStream is) {
    int len;
    byte[] bytes = new byte[1024];
    StringBuffer sb = new StringBuffer();
    try {
        while ((len = is.read(bytes)) != -1) {
            sb.append(new String(bytes, 0, len));
        }

        is.close();
        return sb.toString();
    } catch (IOException e) {
        e.printStackTrace();
    }

    return "";
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值