• android 文件上传


    View Code
    public String postFile(String pathUrl, byte[] data) {
            StringBuilder sbuilder = new StringBuilder();
            try {
                URL url = new URL(pathUrl);
                HttpURLConnection httpConn = (HttpURLConnection) url
                        .openConnection();
                //设置连接属性
                httpConn.setDoOutput(true);// 使用 URL 连接进行输出
                httpConn.setDoInput(true);// 使用 URL 连接进行输入
                httpConn.setUseCaches(false);// 忽略缓存
                httpConn.setRequestMethod("POST");// 设置URL请求方法
    
                // 设置请求属性
                httpConn.setRequestProperty("Content-length", "" + data.length);
                httpConn.setRequestProperty("Content-Type",
                        "application/octet-stream");
                httpConn.setRequestProperty("Connection", "Keep-Alive");
                httpConn.setRequestProperty("Charset", "UTF-8");
    
                // 建立输出流,并写入数据
                OutputStream outputStream = httpConn.getOutputStream();
                outputStream.write(data);
                outputStream.close();
                
                // 获得响应状态
                RESPONSE_CODE = httpConn.getResponseCode();
                if (HttpURLConnection.HTTP_OK == RESPONSE_CODE) {
                    String readLine;
                    BufferedReader responseReader;
                    // 处理响应流,必须与服务器响应流输出的编码一致
                    responseReader = new BufferedReader(new InputStreamReader(
                            httpConn.getInputStream(), "UTF-8"));
                    while ((readLine = responseReader.readLine()) != null) {
                        sbuilder.append(readLine);
                    }
                    responseReader.close();
                }
            } catch (Exception ex) {
                sbuilder.append(ex.getMessage());
                ex.printStackTrace();
            }
            return sbuilder.toString();
        }

     可以直接拷贝下来用。只要将File to byte[]:

    View Code
        public static byte[] getBytesFromFile(File f){
            if(f==null)return null;
            try {
                FileInputStream stream = new FileInputStream(f);
                ByteArrayOutputStream out = new ByteArrayOutputStream(1024);
                byte[] b = new byte[1024];
                for(int n;(n=stream.read(b))!=-1;){
                    out.write(b,0,n);
                }
                stream.close();
                out.close();
                return out.toByteArray();
            } catch (FileNotFoundException e) {
                e.printStackTrace();
            } catch (IOException e) {
                e.printStackTrace();
            }
            return null;
        }
  • 相关阅读:
    nodejs获取服务器数据到页面
    Struts 2
    JQuery
    JDBC
    Hiberbate
    EasyUi
    JavaScript
    利用 HashSet 去过滤元素是否重复
    HTML
    MySQL
  • 原文地址:https://www.cnblogs.com/miya2012/p/2679210.html
Copyright © 2020-2023  润新知