本文要用java.net.HttpURLConnection来实现多个文件上传

1. 研究 form 表单到底封装了什么样的信息发送到servlet。

假如我参数写的内容是hello word,然后二个文件是二个简单的txt文件,form提交的信息为:

-----------------------------7da2e536604c8
Content-Disposition: form-data; name="username" hello word
-----------------------------7da2e536604c8
Content-Disposition: form-data; name="file1"; filename="D:/haha.txt"
Content-Type: text/plain haha
hahaha
-----------------------------7da2e536604c8
Content-Disposition: form-data; name="file2"; filename="D:/huhu.txt"
Content-Type: text/plain messi
huhu
-----------------------------7da2e536604c8--

研究下规律发现有如下几点特征

1.第一行是“ -----------------------------7d92221b604bc ”作为分隔符,然后是“ /r/n ” 回车换行符。 这个7d92221b604bc 分隔符浏览器是随机生成的。

2.第二行是Content-Disposition: form-data; name="file2"; filename="D:/huhu.txt";name=对应input的name值,filename对应要上传的文件名(包括路径在内),

3.第三行如果是文件就有Content-Type: text/plain;这里上传的是txt文件所以是text/plain,如果上穿的是jpg图片的话就是image/jpg了,可以自己试试看看。

然后就是回车换行符。

4.在下就是文件或参数的内容或值了。如:hello word。

5.最后一行是-----------------------------7da2e536604c8--,注意最后多了二个--;

有了这些就可以使用HttpURLConnection来实现上传文件功能了

        private void upload(String[] uploadFiles, String actionUrl) {
String end = "/r/n";
String twoHyphens = "--";
String boundary = "*****";
try {
URL url = new URL(actionUrl);
HttpURLConnection con = (HttpURLConnection) url.openConnection();
// 发送POST请求必须设置如下两行
con.setDoInput(true);
con.setDoOutput(true);
con.setUseCaches(false);
con.setRequestMethod("POST");
con.setRequestProperty("Connection", "Keep-Alive");
con.setRequestProperty("Charset", "UTF-8");
con.setRequestProperty("Content-Type",
"multipart/form-data;boundary=" + boundary);
DataOutputStream ds =
new DataOutputStream(con.getOutputStream());
for (int i = 0; i < uploadFiles.length; i++) {
String uploadFile = uploadFiles[i];
String filename = uploadFile.substring(uploadFile.lastIndexOf("//") + 1);
ds.writeBytes(twoHyphens + boundary + end);
ds.writeBytes("Content-Disposition: form-data; " +
"name=/"file" + i + "/";filename=/"" +
filename + "/"" + end);
ds.writeBytes(end);
FileInputStream fStream = new FileInputStream(uploadFile);
int bufferSize = 1024;
byte[] buffer = new byte[bufferSize];
int length = -1;
while ((length = fStream.read(buffer)) != -1) {
ds.write(buffer, 0, length);
}
ds.writeBytes(end);
/* close streams */
fStream.close();
}
ds.writeBytes(twoHyphens + boundary + twoHyphens + end);
ds.flush();
// 定义BufferedReader输入流来读取URL的响应
InputStream is = con.getInputStream();
int ch;
StringBuffer b = new StringBuffer();
while ((ch = is.read()) != -1) {
b.append((char) ch);
}
String s = b.toString();
if (s.contains("successfully")) {
// for (int i = 1; i < 5; i++) {
int beginIndex = s.indexOf("url =") + 5;
int endIndex = s.indexOf("/n", beginIndex);
String urlStr = s.substring(beginIndex, endIndex).trim();
System.out.println(urlStr);
// }
}
ds.close();
} catch (Exception e) {
}
}

利用HttpURLConnection发送post请求上传多个文件的更多相关文章

  1. el-upload控件一次接口请求上传多个文件

    el-upload组件默认情况下上传多少个文件就会请求多少次上传接口,如何一次上传多个文件而不必多次请求上传接口呢?直接看代码 html <el-upload :action="act ...

  2. elementUI一次请求上传多个文件

    elementui <el-upload                       class="upload-demo"                       ac ...

  3. Java 利用HttpURLConnection发送http请求

    写了一个简单的 Http 请求的Class,实现了 get, post ,postfile package com.asus.uts.util; import org.json.JSONExcepti ...

  4. python发送post请求上传文件,无法解析上传的文件

    前言 近日,在做接口测试时遇到一个奇葩的问题. 使用post请求直接通过接口上传文件,无法识别文件. 遇到的问题 以下是抓包得到的信息: 以上请求是通过Postman直接发送请求的. 在这里可以看到消 ...

  5. Java客户端通过Http发送POST请求上传文件到web服务器

    http://www.cnblogs.com/WilliamJiang/archive/2012/04/29/2475883.html 1.朋友的一个需求,让我给他实现,需求是这样的,需要用ASP.n ...

  6. 利用django如何解析用户上传的excel文件

    https://www.jb51.net/article/119452.htm 前言 我们在工作中的时候,会有这种需求:用户上传一个格式固定excel表格到网站上,然后程序负债解析内容并进行处理.我最 ...

  7. HttpURLConnection 发送http请求帮助类

    java 利用HttpURLConnection 发送http请求 提供GET / POST /上传文件/下载文件 功能 import java.io.*; import java.net.*; im ...

  8. SSM框架下,使用ajax请求上传文件(doc\docx\excel\图片等)

    1.准备工作 1.1.添加上传必要jar包 <dependency> <groupId>commons-io</groupId> <artifactId> ...

  9. 【JAVA】通过HttpURLConnection 上传和下载文件(二)

    HttpURLConnection文件上传 HttpURLConnection采用模拟浏览器上传的数据格式,上传给服务器 上传代码如下: package com.util; import java.i ...

随机推荐

  1. c#特性attribute:

    特性是被编译到metadata中,  是提供给反射用的. 特性attribute:1 什么是attribute,和注释有什么区别 2 声明和使用attribute3 使用attribute完成扩展4 ...

  2. 前端面试问题css汇总

    1,行内元素有哪些?块级元素有哪些?空元素有哪些?CSS的盒模型? 块级元素:div p h1 h2 h3 h4 form ul li 行内元素: a b br i span input select ...

  3. Linux 中的文件锁

    参考资料: https://www.ibm.com/developerworks/cn/linux/l-cn-filelock/index.html

  4. linux shell 重定向中的 & 符号

    写一个简单的 demo 示例 #include <stdio.h> int main() { fprintf(stdout, "stdout output\n"); f ...

  5. 补课:Shell命令${}

    Shell中的${}.##和%%使用范例: 代码如下:file=/dir1/dir2/dir3/my.file.txt可以用${ }分别替换得到不同的值:${file#*/}:删掉第一个 / 及其左边 ...

  6. h5页面适配iPhone X的方法

    一.原生适配iphoneX 原生适配很简单,查看机型图:   只要用 #define KIsiPhoneX ([UIScreen mainScreen].bounds.size.height>8 ...

  7. coocsCreator杂记

    判断是否继承 cc.isChildClassOf = function (subclass, superclass) { 获取所有super classes CCClass.getInheritanc ...

  8. Spark学习笔记-GraphX-1

    Spark学习笔记-GraphX-1 标签: SparkGraphGraphX图计算 2014-09-29 13:04 2339人阅读 评论(0) 收藏 举报  分类: Spark(8)  版权声明: ...

  9. 子数整数(P1151&NOIP水题测试(2017082301))

    题目链接:子数整数 水题,不解释,自己看代码: #include<bits/stdc++.h> using namespace std; int main(){ int k; scanf( ...

  10. 类似 QQ 音乐底部常驻播放栏(AVQueuePlayer)

    一开始搞了个基类,但是这样所有类都要继承它才可以.后来考虑把他加到 window 上.但是在 appdelegate 中没有办法可以加到上面,最后在 keyWindow 的rootViewContro ...