formfile文件上传使用示例
发布时间:2023-06-23 03:41:58
import java.io.BufferedReader;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.OutputStream;
import java.net.InetAddress;
import java.net.Socket;
import java.net.URL;
import java.util.Map;
import android.util.Log;
/**
* 上传的文件
*/
public class FormFile {
private final static String LOGKEY = "FormFile";
/** 上传文件的数据 */
private byte[] data;
private InputStream inStream;
private File file;
/** 文件名称 */
private String filname;
/** 请求参数名称 */
private String parameterName;
/** 内容类型 */
private String contentType = "application/octet-stream";
/**
*
* @param filname
* 文件名称
* @param data
* 上传的文件数据
* @param parameterName
* 参数
* @param contentType
* 内容类型
*/
public FormFile(String filname, byte[] data, String parameterName,
String contentType) {
this.data = data;
this.filname = filname;
this.parameterName = parameterName;
if (contentType != null)
this.contentType = contentType;
}
/**
*
* @param filname
* 文件名
* @param file
* 上传的文件
* @param parameterName
* 参数
* @param contentType
* 内容内容类型
*/
public FormFile(String filname, File file, String parameterName,
String contentType) {
this.filname = filname;
this.parameterName = parameterName;
this.file = file;
try {
this.inStream = new FileInputStream(file);
} catch (FileNotFoundException e) {
e.printStackTrace();
}
if (contentType != null)
this.contentType = contentType;
}
public File getFile() {
return file;
}
public InputStream getInStream() {
return inStream;
}
public byte[] getData() {
return data;
}
public String getFilname() {
return filname;
}
public void setFilname(String filname) {
this.filname = filname;
}
public String getParameterName() {
return parameterName;
}
public void setParameterName(String parameterName) {
this.parameterName = parameterName;
}
public String getContentType() {
return contentType;
}
public void setContentType(String contentType) {
this.contentType = contentType;
}
private String Opertype=null;
public void setOper(String Opertype){
this.Opertype=Opertype;
}
public boolean post(String path, Map<String, String> params)
throws Exception {
final String BOUNDARY = "--------------7da2137580612"; // 数据分隔线
final String endline = "--" + BOUNDARY + "--\r\n";// 数据结束标志
int fileDataLength = 0;
// 得到文件类型数据的总长度
StringBuilder fileExplain = new StringBuilder();
fileExplain.append("--");
fileExplain.append(BOUNDARY);
fileExplain.append("\r\n");
fileExplain.append("Content-Disposition: form-data;name=\""
+ getParameterName() + "\";filename=\"" + getFilname()
+ "\"\r\n");
fileExplain.append("Content-Type: " + getContentType() + "\r\n\r\n");
fileExplain.append("\r\n");
fileDataLength += fileExplain.length();
if (getInStream() != null) {
fileDataLength += getFile().length();
} else {
fileDataLength += getData().length;
}
StringBuilder textEntity = new StringBuilder();
for (Map.Entry<String, String> entry : params.entrySet()) {//构造文本类型参数的实体数据
textEntity.append("--");
textEntity.append(BOUNDARY);
textEntity.append("\r\n");
textEntity.append("Content-Disposition: form-data; name=\""
+ entry.getKey() + "\"\r\n\r\n");
textEntity.append(entry.getValue());
textEntity.append("\r\n");
}
Log.v(LOGKEY, textEntity.toString());
// 计算传输给服务器的实体数据总长度
int dataLength = textEntity.toString().getBytes().length
+ fileDataLength + endline.getBytes().length;
URL url = new URL(path);
Log.v(LOGKEY, url.toString());
int port = url.getPort() == -1 ? 80 : url.getPort();
Socket socket = new Socket(InetAddress.getByName(url.getHost()), port);
OutputStream outStream = socket.getOutputStream();
// 下面完成HTTP请求头的发送
String requestmethod = "POST " + url.getPath()+"?"+Opertype + " HTTP/1.1\r\n";
Log.v(LOGKEY, requestmethod);
outStream.write(requestmethod.getBytes());
String accept = "Accept: image/gif, image/jpeg, image/pjpeg, image/pjpeg, application/x-shockwave-flash, application/xaml+xml, application/vnd.ms-xpsdocument, application/x-ms-xbap, application/x-ms-application, application/vnd.ms-excel, application/vnd.ms-powerpoint, application/msword, */*\r\n";
outStream.write(accept.getBytes());
String language = "Accept-Language: zh-CN\r\n";
outStream.write(language.getBytes());
String contenttype = "Content-Type: multipart/form-data; boundary="
+ BOUNDARY + "\r\n";
outStream.write(contenttype.getBytes());
String contentlength = "Content-Length: " + dataLength + "\r\n";
outStream.write(contentlength.getBytes());
String alive = "Connection: Keep-Alive\r\n";
outStream.write(alive.getBytes());
String host = "Host: " + url.getHost() + ":" + port + "\r\n";
outStream.write(host.getBytes());
// 写完HTTP请求头后根据HTTP协议再写一个回车换行
outStream.write("\r\n".getBytes());
// 把所有文本类型的实体数据发送出来
outStream.write(textEntity.toString().getBytes());
// 把所有文件类型的实体数据发送出来
StringBuilder fileEntity = new StringBuilder();
fileEntity.append("--");
fileEntity.append(BOUNDARY);
fileEntity.append("\r\n");
fileEntity.append("Content-Disposition: form-data;name=\""
+ getParameterName() + "\";filename=\"" + getFilname()
+ "\"\r\n");
fileEntity.append("Content-Type: " + getContentType() + "\r\n\r\n");
outStream.write(fileEntity.toString().getBytes());
if (getInStream() != null) {
byte[] buffer = new byte[1024];
int len = 0;
while ((len = getInStream().read(buffer, 0, 1024)) != -1) {
outStream.write(buffer, 0, len);
}
getInStream().close();
} else {
outStream.write(getData(), 0, getData().length);
}
outStream.write("\r\n".getBytes());
// 下面发送数据结束标志,表示数据已经结束
outStream.write(endline.getBytes());
BufferedReader reader = new BufferedReader(new InputStreamReader(socket.getInputStream()));
if (reader.readLine().indexOf("200") == -1) {// 读取web服务器返回的数据,判断请求码是否为200,如果不是200,代表请求失败
return false;
}
outStream.flush();
outStream.close();
reader.close();
socket.close();
return true;
}
}
//测试代码
File iconFile = new File("file路径");
String url="htttp://192.168.1.101:8080/APP/initServlet";
Map<String, String> map = new HashMap<String, String>();//表单内容
map.put("name","blog");
if (iconFile != null) {
FormFile uploadfile = new FormFile(iconFile.getName(),
iconFile, "iconfile", "image/jpeg");
uploadfile.setOper("action=insertusr");//在url上插入?action=insertusr
try {
boolean isok = uploadfile.post(url, map);
} catch (Exception e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
猜你喜欢
- 很多时候我们开发的软件需要向用户提供软件参数设置功能,例如我们常用的QQ,用户可以设置是否允许陌生人添加自己为好友。对于软件配置参数的保存,
- 自从SEOTcs系统11月份24日更新了一下SEO得分算法以来,一直困扰我的一个问题出现了,java的数据job任务,在执行过程中会经常报以
- 上一节《SSH框架网上商城项目第1战之整合Struts2、Hibernate4.3和Spring4.2》我们搭建好了Struts2、Hibe
- 相比于直线检测,直线拟合的最大特点是将所有数据只拟合出一条直线void fitLine( InputArray points, Output
- 前言通过此篇文章,你将了解到:Flutter windows和Android桌面应用屏幕适配的解决方案;屏幕适配的相关知识和原理;flutt
- 这篇文章主要介绍了Java如何实现自定义异常类,文中通过示例代码介绍的非常详细,对大家的学习或者工作具有一定的参考学习价值,需要的朋友可以参
- 本文实例讲述了C++语言实现线性表之链表实现方法。分享给大家供大家参考。具体分析如下:插入、删除结点的代码有点多,但这样提高了代码的可读性,
- 介绍什么是ThreadLocal?ThreadLocal叫做线程变量,用于在多线程环境下创建线程本地变量。通俗的讲,ThreadLocal可
- Note:这篇文章是基于Android Studio 3.01版本的,NDK是R16。step1:创建一个包含C++的项目其他默认就可以了。
- 1.ArrayList 是基数组结构的,需要连续的内存空间从构造函数可以看出,ArrayList内部用一个Object数组来保存数据。对于无
- 这篇会深化View拖拽实例,利用Flutter Animation、插值器以及AnimatedBuilder教大家实现带动画的抽屉效果。先来
- 已知两个链表list1和list,2,各自非降序排列,将它们合并成另外一个链表list3,并且依然有序,要求保留所有节点。实现过程中,lis
- 一、写在前面 数据结构中的队列应该是比较熟悉的
- 正则表达式是一种描述词素的重要表示方法。虽然正则表达式并不能表达出所有可能的模式(例如“由等数量的 a 和 b 组成的字符串”),但是它可以
- 1、volley 项目地址 https://github.com/smanikandan14/Volley-demo (1)&nb
- 在观察者模式中有2个要素:一个是被观察对象,另一个是观察者。但被观察对象的状态发生改变会通知观察者。举例:把订阅报纸的人看作是观察者,把报纸
- 项目概况:Spring Cloud搭的微服务,使用了eureka,FeignClient,现在遇到FeignClient调用接口时不支持上传
- 前言 因为自己在做的一个小软件里面需要用到从A-Z排序的ListView,所以自然而然的想到了微信的联系人,我想要的就是那样的效果。本来没
- 1. 在原有工程目录右键-> new ->Module->:2. 选择library:3. 一路next,最后finish
- 本文实例讲述了C#中HttpWebRequest的用法。分享给大家供大家参考。具体如下:HttpWebRequest类主要利用HTTP 协议