java文件上传报文解析与实现

  • 2019 年 10 月 30 日
  • 筆記

版权声明:本文为博主原创文章,遵循 CC 4.0 BY-SA 版权协议,转载请附上原文出处链接和本声明。

本文链接:https://blog.csdn.net/luo4105/article/details/75561101

文件上传用web实现很容易,只需要在form加上enctype="multipart/form-data"就可以。

用java实现也很简单,注意一下请求报文格式就好了。

首先我们看一下报文数据

POST /epg/admin/epg/originalfile/upload.doHTTP/1.1    Accept-Encoding: gzip, deflate  Content-Length: 3714479  Content-Type: multipart/form-data;boundary=---------------------------161393124728552  Cookie:JSESSIONID=892218FFF1CD71AA8A4A2E8A52FA2BBA  Host: 192.168.1.107:8090  Connection: keep-alive    -----------------------------161393124728552  Content-Disposition: form-data;name="file"; filename="17df-x0hjki.xml"  Content-Type: text/xml    <?xml version="1.0"encoding="UTF-8"?><tv>  /** 文件数据 */</tv>  -----------------------------161393124728552  Content-Disposition: form-data;name="sourceId"    2  -----------------------------161393124728552--
POST /epg/admin/epg/originalfile/upload.doHTTP/1.1

代表这是post提交的

Content-Type: multipart/form-data;boundary=---------------------------161393124728552  Cookie:JSESSIONID=892218FFF1CD71AA8A4A2E8A52FA2BBA  Connection: keep-alive

这三个是需要手动自己添加设置的,第一句是代表类型是文件,boundary是参数的分隔符,使用时在前面加上”–”。

第二行是登陆验证需要的。

第三行是保持连接的。

-----------------------------161393124728552  Content-Disposition: form-data;name="file"; filename="17df-x0hjki.xml"  Content-Type: text/xml    <?xml version="1.0"encoding="UTF-8"?><tv>  /** 文件数据 */</tv>  -----------------------------161393124728552  Content-Disposition: form-data;name="sourceId"    2  -----------------------------161393124728552--

这是数据报文

第一行是”—“+ boundary分隔符,

第二行是文件的名称,后台接受的参数名

第三行是文件类型

第四行是空格,代码中是”n”

第五行开始是文件内容

第二部分是表单参数的值

最后注意一下结尾,是”–”+boundary+”—“

这里用HttpConnection实现

public static void uploadFile(String fileName) {      try {            // 换行符          final StringnewLine = "rn";          final String boundaryPrefix = "--";          // 定义数据分隔线          String BOUNDARY = "----WebKitFormBoundaryAvVfvFPWnCBmJzQ5";          // 服务器的域名          URL url = new URL("http://192.168.1.107:8090/epg/admin/epg/originalfile/upload.do");          HttpURLConnection conn = (HttpURLConnection)url.openConnection();          // 设置为POST情          conn.setRequestMethod("POST");          // 发送POST请求必须设置如下两行          conn.setDoOutput(true);          conn.setDoInput(true);          // 设置请求头参数          conn.setRequestProperty("connection", "Keep-Alive");          conn.setRequestProperty("Content-Type", "multipart/form-data;boundary=" + BOUNDARY);          conn.setRequestProperty("Content-Length", "3714479");          conn.setRequestProperty("Cookie", "JSESSIONID=CEA219E45CC9894D59D9F07FBD8597C6");          conn.setRequestProperty("User-Agent", "Mozilla/5.0(Windows NT 6.1; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko)Chrome/59.0.3071.115 Safari/537.36");            OutputStream out = new DataOutputStream(conn.getOutputStream());              StringBuilder sb2 = new StringBuilder();          sb2.append(boundaryPrefix + BOUNDARY + newLine);          // 文件参数,photo参数名可以随意修改          sb2.append("Content-Disposition:form-data; name="sourceId"");          // 参数头设置完以后需要两个换行,然后才是参数内容          sb2.append(newLine);          sb2.append(newLine);          sb2.append(2);            // 将参数头的数据写入到输出流中          out.write(sb2.toString().getBytes());            // 上传文件          File file = new File(fileName);          StringBuilder sb = new StringBuilder();          sb.append(newLine + boundaryPrefix + BOUNDARY + newLine);          // 文件参数,参数名可以随意修改          sb.append("Content-Disposition:form-data; name="file";filename="" + file.getName()                  + """);          sb.append(newLine + "Content-Type: text/xml");          // 参数头设置完以后需要两个换行,然后才是参数内容          sb.append(newLine);          sb.append(newLine);          out.write(sb.toString().getBytes());            // 数据输入流,用于读取文件数据          DataInputStream in = new DataInputStream(new FileInputStream(                  file));          byte[] bufferOut = new byte[1024];          int bytes = 0;          // 每次读1KB数据,并且将文件数据写入到输出流中          while ((bytes= in.read(bufferOut)) != -1) {              out.write(bufferOut, 0, bytes);          }          // 最后添加换行          in.close();            System.out.println(sb.toString());          System.out.println(sb2.toString());            // 定义最后数据分隔线,即--加上BOUNDARY再加上--。          byte[]end_data = (newLine + boundaryPrefix + BOUNDARY + boundaryPrefix + newLine)                  .getBytes();          // 写上结尾标识          out.write(end_data);          out.flush();          out.close();            // 定义BufferedReader输入流来读取URL的响应          BufferedReader reader = new BufferedReader(new InputStreamReader(                  conn.getInputStream()));          String line = null;          while ((line = reader.readLine()) != null) {              System.out.println(line);          }      } catch (Exceptione) {          System.out.println("发送POST请求出现异常!"+ e);          e.printStackTrace();      }  }