首页 > 编程语言 >Java上传二进制(multipart/form-data)_Demo

Java上传二进制(multipart/form-data)_Demo

时间:2023-03-02 16:33:05浏览次数:45  
标签:end String form Java writeBytes null data ds httpURLConnection

这里做个记录,通过此次问题的解决,弄清POST同时传文件及参数时,底层到底是怎么组成,文件流及参数是怎么分隔组成,及分隔符如何写入流。

好,废话不多说,直接上代码,此代码配置好自己参数可直接调试,无需引入更多包。

  1 package com.hhb;
  2 import java.io.*;
  3 import java.net.HttpURLConnection;
  4 import java.net.URL;
  5 import java.net.URLConnection;
  6 public class upoad {
  7     public static void main(String[] args) {
  8         System.out.println("上传开始");
  9         //要上传的图片
 10         String uploadFilePaths = "D:\\loadFile.jpg";
 11         //请求上传图片API地址
 12         String actionUrl = "https://localhost/api/File/UploadFile";
 13 
 14         //参数 Rax 随机数(10位数)。TimeUtc 时间戳(秒级别)
 15         String Scope = "TrackReceipt";
 16         String Rax = "5tqczr48id";
 17         String TimeUtc = "1677722176";
 18         String token = "eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9.eyJodHRwOi8vc2NoZW1hcy5taWNyb3NvZnQuY29tL3dzLzIwMDgvMDYvaWRlbnRpdHkvY2xhaW1zL3ByaW1hcnlzaWQiOiIzYTA5YjIxMC04OGE3LWE4MDItY2Y1Mi1iOGI2YzhjNDE1OTMiLCJodHRwOi8vc2NoZW1hcy54bWxzb2FwLm9yZy93cy8yMDA1LzA1L2lkZW50aXR5L2NsYWltcy9zaWQiOiIwOGRhZjgyYy01M2Q4LTQxZTQtODAzOC1kMmUyMDkyMmNhM2MiLCJuYmYiOjE2Nzc3MTk3NDQsImV4cCI6MTY4MDMxMTc0NCwiaXNzIjoib2NlbG90IiwiYXVkIjoiaGNkIn0.erl5opo0tie-MVmEMQYYoaGkIs-LbbftYREoHAfyzJg";
 19         //调用
 20         String rel = uploadFile(actionUrl, uploadFilePaths, Scope, Rax, TimeUtc, token);
 21         System.out.println("返回结果:" + rel);
 22     }
 23 
 24     /**
 25      * 多文件上传的方法
 26      *
 27      * @param actionUrl:上传的路径
 28      * @param uploadFilePaths:需要上传的文件路径,数组
 29      * @return
 30      */
 31     @SuppressWarnings("finally")
 32     public static String uploadFile(String actionUrl, String uploadFilePaths, String Scope
 33             , String Rax, String TimeUtc, String token) {
 34         String end = "\r\n";
 35         String twoHyphens = "--";
 36         String boundary = "*****";
 37 
 38         DataOutputStream ds = null;
 39         InputStream inputStream = null;
 40         InputStreamReader inputStreamReader = null;
 41         BufferedReader reader = null;
 42         StringBuffer resultBuffer = new StringBuffer();
 43         String tempLine = null;
 44         token = "Bearer " + token;
 45 
 46         String uploadFile = uploadFilePaths;
 47         String filename = uploadFile.substring(uploadFile.lastIndexOf("\\") + 1);
 48 
 49         try {
 50             // 统一资源
 51             URL url = new URL(actionUrl);
 52             // 连接类的父类,抽象类
 53             URLConnection urlConnection = url.openConnection();
 54             // http的连接类
 55             HttpURLConnection httpURLConnection = (HttpURLConnection) urlConnection;
 56             // 设置是否从httpUrlConnection读入,默认情况下是true;
 57             httpURLConnection.setDoInput(true);
 58             // 设置是否向httpUrlConnection输出
 59             httpURLConnection.setDoOutput(true);
 60             // Post 请求不能使用缓存
 61             httpURLConnection.setUseCaches(false);
 62             // 设定请求的方法,默认是GET
 63             httpURLConnection.setRequestMethod("POST");
 64             // 设置字符编码连接参数
 65             httpURLConnection.setRequestProperty("Connection", "Keep-Alive");
 66             // 设置字符编码
 67             httpURLConnection.setRequestProperty("Charset", "UTF-8");
 68             // 设置请求内容类型
 69             httpURLConnection.setRequestProperty("Authorization", token);
 70 
 71             httpURLConnection.setRequestProperty("Content-Type", "multipart/form-data;boundary=" + boundary);
 72 
 73             // 设置DataOutputStream
 74             ds = new DataOutputStream(httpURLConnection.getOutputStream());
 75 
 76             //封装键值对数据一
 77             ds.writeBytes(twoHyphens + boundary + end);
 78             ds.writeBytes("Content-Disposition: form-data; name=\"" + "Scope" + "\"");
 79             ds.writeBytes(end);
 80 //            ds.writeBytes("Content-Type: " + "text/plain");
 81 //            ds.writeBytes(end);
 82 //            ds.writeBytes("Content-Lenght: " + ("" + Scope).length());
 83 //            ds.writeBytes(end);
 84             ds.writeBytes(end);
 85             ds.writeBytes("" + Scope);
 86             ds.writeBytes(end);
 87 
 88 
 89             //封装键值对数据三
 90             ds.writeBytes(twoHyphens + boundary + end);
 91             ds.writeBytes("Content-Disposition: form-data; name=\"" + "Rax" + "\"");
 92             ds.writeBytes(end);
 93             ds.writeBytes(end);
 94             ds.writeBytes("" + Rax);
 95             ds.writeBytes(end);
 96 
 97             //封装键值对数据四
 98             ds.writeBytes(twoHyphens + boundary + end);
 99             ds.writeBytes("Content-Disposition: form-data; name=\"" + "TimeUtc" + "\"");
100             ds.writeBytes(end);
101             ds.writeBytes(end);
102             ds.writeBytes("" + TimeUtc);
103             ds.writeBytes(end);
104 
105             //封装图片数据
106             ds.writeBytes(twoHyphens + boundary + end);
107             ds.writeBytes("Content-Disposition: form-data; " + "name=\"File\";filename=\"" + filename
108                     + "\"" + end);
109             ds.writeBytes("Content-Type: " + "image/jpeg" + end);
110             //ds.writeBytes("Content-Lenght: "+file.length()+ end);
111             ds.writeBytes(end);
112             FileInputStream fStream = new FileInputStream(uploadFile);
113             int bufferSize = 1024;
114             byte[] buffer = new byte[bufferSize];
115             int length = -1;
116             while ((length = fStream.read(buffer)) != -1) {
117                 ds.write(buffer, 0, length);
118             }
119             ds.writeBytes(end);
120             /* close streams */
121             fStream.close();
122             //输入结束
123             ds.writeBytes(twoHyphens + boundary + twoHyphens + end);
124             /* close streams */
125             ds.flush();
126             if (httpURLConnection.getResponseCode() >= 300) {
127                 throw new Exception(
128                         "HTTP Request is not success, Response code is " + httpURLConnection.getResponseCode());
129             }
130             if (httpURLConnection.getResponseCode() == HttpURLConnection.HTTP_OK) {
131                 inputStream = httpURLConnection.getInputStream();
132                 inputStreamReader = new InputStreamReader(inputStream);
133                 reader = new BufferedReader(inputStreamReader);
134                 tempLine = null;
135                 resultBuffer = new StringBuffer();
136                 while ((tempLine = reader.readLine()) != null) {
137                     resultBuffer.append(tempLine);
138                     resultBuffer.append("\n");
139                 }
140             }
141         } catch (Exception e) {
142             e.printStackTrace();
143         } finally {
144             if (ds != null) {
145                 try {
146                     ds.close();
147                 } catch (IOException e) {
148                     // TODO Auto-generated catch block
149                     e.printStackTrace();
150                 }
151             }
152             if (reader != null) {
153                 try {
154                     reader.close();
155                 } catch (IOException e) {
156                     // TODO Auto-generated catch block
157                     e.printStackTrace();
158                 }
159             }
160             if (inputStreamReader != null) {
161                 try {
162                     inputStreamReader.close();
163                 } catch (IOException e) {
164                     // TODO Auto-generated catch block
165                     e.printStackTrace();
166                 }
167             }
168             if (inputStream != null) {
169                 try {
170                     inputStream.close();
171                 } catch (IOException e) {
172                     // TODO Auto-generated catch block
173                     e.printStackTrace();
174                 }
175             }
176             return resultBuffer.toString();
177         }
178     }
179 }
参考:http://www.manongjc.com/detail/26-ibpgtovosforqma.html
https://blog.csdn.net/AP0906424/article/details/108998071

标签:end,String,form,Java,writeBytes,null,data,ds,httpURLConnection
From: https://www.cnblogs.com/tjdk/p/17172258.html

相关文章

  • 火山引擎 DataLeap:揭秘字节跳动数据血缘架构演进之路
    更多技术交流、求职机会,欢迎关注字节跳动数据平台微信公众号,回复【1】进入官方交流群DataLeap是火山引擎数智平台VeDI旗下的大数据研发治理套件产品,帮助用户快速完成......
  • DataEase 集成 CAS 实现用户单点登录
    场景介绍随着企业IT场景越来越复杂,应用平台不断增加,用户需要管理每个应用平台的登录信息;用户集中管理平台(如:“LDAP”)可以使用户在所有应用平台使用同一个用户名进行登录;而......
  • Java应用【Ⅺ】在 Java 中使用MyBatis框架进行关系型数据库操作
    如果您觉得本博客的内容对您有所帮助或启发,请关注我的博客,以便第一时间获取最新技术文章和教程。同时,也欢迎您在评论区留言,分享想法和建议。谢谢支持!相关阅读:​​Java应用【......
  • java - 跳转控制17
    packagecom.demo.test;importjava.util.Scanner;publicclassskip{publicstaticvoidmain(String[]args){Scannersc=newScanner(System.in......
  • java swing Jpanel
    “`packagecom.js;importjava.awt.*;importjavax.swing.*;publicclassJava_3_swing_8_JPanelextendsJFrame{publicJava_3_swing_8_JPanel(){Container......
  • java swing 网格布局
    “`packagecom.js;importjava.awt.*;importjavax.swing.*;publicclassJava_3_swing_7_GridLayoutextendsJFrame{publicJava_3_swing_7_GridLayout(){Co......
  • java 类的高级特性
    类的高级特性1类包1.1类名冲突类包的存在就是为了解决类名的冲突,就是重名。1.2完整的类路径例如:java.uitl.Date=newjava.util.Date();java.sql.Date=new......
  • JavaSE API
    JavaSEAPI排序java.lang.Comparablejava.lang.Comparatorjava.lang.Object它是所有类型的根父类一个类如果没有显式声明它的父类,这个类的直接父类就是Object理解......
  • Java 匿名内部类
    什么是匿名内部类匿名类是一个表达式,在定义的最后用分号";"结束匿名内部类可以使你的代码更加简洁,你可以在定义一个类的同时对其进行实例化。它与局部类很相似,不同的是它......
  • why is the setInterval task executed slower than the setTimeout task in the brow
    whyisthesetIntervaltaskexecutedslowerthanthesetTimeouttaskinthebrowserjavascriptenvironment?为什么在浏览器javascript环境下setInterval任务......