Android笔记之HttpURLConnection上传文件到服务器

1、主代码:

public static String uploadFile(String path, File file,
            Map<String, String> map, String encode) {
        String result = null;
        String BOUNDARY = UUID.randomUUID().toString(); // 边界标识 随机生成
        String PREFIX = "--", LINE_END = "
";
        String CONTENT_TYPE = "multipart/form-data"; // 内容类型

        try {
            URL url = new URL(path);
            HttpURLConnection conn = (HttpURLConnection) url.openConnection();
            conn.setReadTimeout(3000);
            conn.setConnectTimeout(3000);
            conn.setDoInput(true); // 允许输入流
            conn.setDoOutput(true); // 允许输出流
            conn.setUseCaches(false); // 不允许使用缓存
            conn.setRequestMethod("POST"); // 请求方式
            conn.setRequestProperty("Charset", encode); // 设置编码
            conn.setRequestProperty("connection", "keep-alive");
            conn.setRequestProperty("Content-Type", CONTENT_TYPE + ";boundary="+ BOUNDARY);

            DataOutputStream dos = new DataOutputStream(
                    conn.getOutputStream());

            if (file != null) {
                /**
                 * 当文件不为空,把文件包装并且上传
                 */

                StringBuffer sb = new StringBuffer();
                sb.append(PREFIX);
                sb.append(BOUNDARY);
                sb.append(LINE_END);
                /**
                 * 这里重点注意: name里面的值为服务器端需要key 只有这个key 才可以得到对应的文件
                 * filename是文件的名字,包含后缀名的 比如:abc.png
                 */

                sb.append("Content-Disposition: form-data; name="img"; filename=""
                        + file.getName() + """ + LINE_END);
                sb.append("Content-Type: application/octet-stream; charset="
                        + encode + LINE_END);
                sb.append(LINE_END);
                dos.write(sb.toString().getBytes());
                InputStream is = new FileInputStream(file);
                byte[] bytes = new byte[1024];
                int len = 0;
                while ((len = is.read(bytes)) != -1) {
                    dos.write(bytes, 0, len);
                }
                is.close();
                dos.write(LINE_END.getBytes());
                byte[] end_data = (PREFIX + BOUNDARY + PREFIX + LINE_END)
                        .getBytes();
                
                dos.write(end_data);
                dos.flush();
                /**
                 * 获取响应码 200=成功 当响应成功,获取响应的流
                 */
                int res = conn.getResponseCode();
                Log.e("Upload", "response code:" + res);
                // if(res==200)
                // {
                Log.e("Upload", "request success");
                InputStream input = conn.getInputStream();
                StringBuffer sb1 = new StringBuffer();
                int ss;
                while ((ss = input.read()) != -1) {
                    sb1.append((char) ss);
                }
                result = sb1.toString();
                Log.e("Upload", "result : " + result);
            }
        } catch (MalformedURLException e) {
            e.printStackTrace();
        } catch (IOException e) {
            e.printStackTrace();
        }
        return result;
    }

2、选择图片的入口

                Intent getImage = new Intent(Intent.ACTION_GET_CONTENT);
                // getImage.addCategory(Intent.CATEGORY_OPENABLE);
                /*
                 * 通过拍照获取图片 Intent getImageByCamera =
                 * newIntent("android.media.action.IMAGE_CAPTURE");
                 */
                // 通过图库选择图片
                getImage.setType("image/jpeg");
                startActivityForResult(getImage, 0);
           
........
Map<String, String> map = new HashMap<String, String>();
                File f = new File(picPath);
                Log.i("FileName", f.getName());
                // map.put("file", picPath);
                map.put("id", "0");
                try {
                    FormFile.post(CommonUrl.Upload_URL, map, f);
                } catch (Exception e) {
                    // TODO Auto-generated catch block
                    e.printStackTrace();
                }
........
@Override
protected void onActivityResult(int requestCode, int resultCode, Intent intent) { // TODO Auto-generated method stub if (requestCode == 0) { try { uri = intent.getData(); imageView.setImageURI(uri); Log.i("getData", intent.getData().toString()); System.out.println("requestCode=" + requestCode); String[] pojo = { MediaStore.Images.Media.DATA }; Cursor cursor = managedQuery(uri, pojo, null, null, null); if (cursor != null) { System.out.println("cursor不为空!"); ContentResolver cr = this.getContentResolver(); int colunm_index = cursor .getColumnIndexOrThrow(MediaStore.Images.Media.DATA); cursor.moveToFirst(); String path = cursor.getString(colunm_index); /*** * 这里加这样一个判断主要是为了第三方的软件选择,比如:使用第三方的文件管理器的话,你选择的文件就不一定是图片了, * 这样的话,我们判断文件的后缀名 如果是图片格式的话,那么才可以 */ if (path.endsWith("jpg") || path.endsWith("png")) { picPath = path; Bitmap bitmap = BitmapFactory.decodeStream(cr .openInputStream(uri)); imageView.setImageBitmap(bitmap); } else { } System.out.println("picPath---" + picPath); } } catch (Exception e) { System.out.println(e.getMessage()); } } else { } // 把得到的图片绑定在控件上显示 }

Done!

原文地址:https://www.cnblogs.com/xingyyy/p/3394101.html