美文网首页
【安卓笔记】上传文件到服务器

【安卓笔记】上传文件到服务器

作者: 九狼JIULANG | 来源:发表于2021-10-03 17:20 被阅读0次

    java

       private String uploadFile(String uploadUrl, String filename) {
            String end = "\r\n";
            String twoHyphens = "--";
            String boundary = "******";
            try {
                URL url = new URL(uploadUrl);
                HttpURLConnection httpURLConnection = (HttpURLConnection) url.openConnection();
                // 设置每次传输的流大小,可以有效防止手机因为内存不足崩溃
                // 此方法用于在预先不知道内容长度时启用没有进行内部缓冲的 HTTP 请求正文的流。
                httpURLConnection.setChunkedStreamingMode(128 * 102400);// 128K
                // 允许输入输出流
                httpURLConnection.setDoInput(true);
                httpURLConnection.setDoOutput(true);
                httpURLConnection.setUseCaches(false);
                // 使用POST方法
                httpURLConnection.setRequestMethod("POST");
                httpURLConnection.setRequestProperty("Connection", "Keep-Alive");
                httpURLConnection.setRequestProperty("Charset", "UTF-8");
                httpURLConnection.setRequestProperty("Content-Type",
                        "multipart/form-data;boundary=" + boundary);
                DataOutputStream dos = new DataOutputStream(httpURLConnection.getOutputStream());
                dos.writeBytes(twoHyphens + boundary + end);
                dos.writeBytes("Content-Disposition: form-data; name=\"file\"; filename=\"" + filename.substring(filename.lastIndexOf("/") + 1)
                        + "\""
                        + end);
                dos.writeBytes(end);
    
                FileInputStream fis = new FileInputStream(filename);
                byte[] buffer = new byte[81920000]; // 8k
                int count = 0;
                // 读取文件
                while ((count = fis.read(buffer)) != -1) {
                    dos.write(buffer, 0, count);
                }
                fis.close();
    
                dos.writeBytes(end);
                dos.writeBytes(twoHyphens + boundary + twoHyphens + end);
                dos.flush();
    
                InputStream is = httpURLConnection.getInputStream();
                InputStreamReader isr = new InputStreamReader(is, "utf-8");
                BufferedReader br = new BufferedReader(isr);
                String result = br.readLine();
    
    
                dos.close();
                is.close();
                return result;
            } catch (Exception e)  {
                e.printStackTrace();
                return e.getMessage();
            }
        }
    

    相关文章

      网友评论

          本文标题:【安卓笔记】上传文件到服务器

          本文链接:https://www.haomeiwen.com/subject/vxzmnltx.html