代码可实现文本域及非文本域的处理

请求代码:

/**
* 上传
*
* @param urlStr
* @param textMap
* @param fileMap
* @return
*/
public static String formUpload(String urlStr, Map<String, String> textMap,
Map<String, String> fileMap) {
String res = "";
HttpURLConnection conn = null;
String BOUNDARY = "---------------------------123821742118716"; //boundary就是request头和上传文件内容的分隔符
try {
URL url = new URL(urlStr);
conn = (HttpURLConnection) url.openConnection();
conn.setConnectTimeout(5000);
conn.setReadTimeout(30000);
conn.setDoOutput(true);
conn.setDoInput(true);
conn.setUseCaches(false);
conn.setRequestMethod("POST");
conn.setRequestProperty("Connection", "Keep-Alive");
conn
.setRequestProperty("User-Agent",
"Mozilla/5.0 (Windows; U; Windows NT 6.1; zh-CN; rv:1.9.2.6)");
conn.setRequestProperty("Content-Type",
"multipart/form-data; boundary=" + BOUNDARY); OutputStream out = new DataOutputStream(conn.getOutputStream());
// text
if (textMap != null) {
StringBuffer strBuf = new StringBuffer();
Iterator iter = textMap.entrySet().iterator();
while (iter.hasNext()) {
Map.Entry entry = (Map.Entry) iter.next();
String inputName = (String) entry.getKey();
String inputValue = (String) entry.getValue();
if (inputValue == null) {
continue;
}
strBuf.append("\r\n").append("--").append(BOUNDARY).append(
"\r\n");
strBuf.append("Content-Disposition: form-data; name=\""
+ inputName + "\"\r\n\r\n");
strBuf.append(inputValue);
}
out.write(strBuf.toString().getBytes());
} // file
if (fileMap != null) {
Iterator iter = fileMap.entrySet().iterator();
while (iter.hasNext()) {
Map.Entry entry = (Map.Entry) iter.next();
String inputName = (String) entry.getKey();
String inputValue = (String) entry.getValue();
if (inputValue == null) {
continue;
}
File file = new File(inputValue);
String filename = file.getName();
String contentType = new MimetypesFileTypeMap()
.getContentType(file);
if (filename.endsWith(".png")) {
contentType = "image/png";
}
if (contentType == null || contentType.equals("")) {
contentType = "application/octet-stream";
} StringBuffer strBuf = new StringBuffer();
strBuf.append("\r\n").append("--").append(BOUNDARY).append(
"\r\n");
strBuf.append("Content-Disposition: form-data; name=\""
+ inputName + "\"; filename=\"" + filename
+ "\"\r\n");
strBuf.append("Content-Type:" + contentType + "\r\n\r\n"); out.write(strBuf.toString().getBytes()); DataInputStream in = new DataInputStream(
new FileInputStream(file));
int bytes = 0;
byte[] bufferOut = new byte[1024];
while ((bytes = in.read(bufferOut)) != -1) {
out.write(bufferOut, 0, bytes);
}
in.close();
}
} byte[] endData = ("\r\n--" + BOUNDARY + "--\r\n").getBytes();
out.write(endData);
out.flush();
out.close(); // 读取返回数据
StringBuffer strBuf = new StringBuffer();
BufferedReader reader = new BufferedReader(new InputStreamReader(
conn.getInputStream()));
String line = null;
while ((line = reader.readLine()) != null) {
strBuf.append(line).append("\n");
}
res = strBuf.toString();
reader.close();
reader = null;
} catch (Exception e) {
System.out.println("发送POST请求出错。" + urlStr);
e.printStackTrace();
} finally {
if (conn != null) {
conn.disconnect();
conn = null;
}
}
return res;
}

  处理上传请求代码:

/**
* 上传
* @param request
* @param response
* @throws Exception
*/
public void doUpload(HttpServletRequest request, HttpServletResponse response)throws Exception {
String jsession = request.getParameter("jsessionid");
System.out.println(jsession);
HttpSession s = request.getSession();
System.out.println(s.getId());
DiskFileItemFactory factory = new DiskFileItemFactory();
// 设置内存缓冲区,超过后写入临时文件
factory.setSizeThreshold(10240000);
ServletFileUpload upload = new ServletFileUpload(factory);
// 设置单个文件的最大上传值
upload.setFileSizeMax(10002400000l);
// 设置整个request的最大值
upload.setSizeMax(10002400000l);
upload.setHeaderEncoding("UTF-8");
//Date now = new Date();
Map map = new HashMap();
File tmpFile = new File(tmpFilePath);
if(!tmpFile.exists())
tmpFile.mkdirs();
List items = null;
try {
items = upload.parseRequest(request);
} catch (FileUploadException e) {
throw new RuntimeException(e);
}
if (items == null)
return ;
Date date = new Date();
Iterator iter = items.iterator(); String fileName = tmpFilePath + File.separator +date.getTime(); while (iter.hasNext()) {// 循环获得每个表单项
FileItem item = (FileItem) iter.next();
if (item.isFormField()) {
String name = item.getFieldName();
try {
String value = item.getString("utf-8");// 如果参数里面有中文,防止出现乱码
map.put(name, value);
} catch (UnsupportedEncodingException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}else if(item.getName().length() > 0) {
String namefix = item.getName();
namefix = namefix.substring(namefix.lastIndexOf("."));
fileName = fileName +namefix;
item.write(new File(fileName));
} }
String type =(String) map.get("type");
if(type.equals("war")){
request.getSession().setAttribute("warFileName",fileName);
}else if(type.equals("sql")){
request.getSession().setAttribute("sqlFileName",fileName);
}
try {
map.put("data", fileName);
response.getWriter().write(JsonUtils.convertToString(map));
} catch (IOException e) {
e.printStackTrace();
} }

  测试调用代码:

/**
* @param args
*/
public static void main(String[] args) { String filepath="D:\\test\\PPGhost.war"; String urlStr = "http://localhost:8080/iopm/version/add.do?method=upload"; Map<String, String> textMap = new HashMap<String, String>(); textMap.put("name", "testname");
textMap.put("type", "war"); Map<String, String> fileMap = new HashMap<String, String>(); fileMap.put("userfile", filepath); String ret = formUpload(urlStr, textMap, fileMap); System.out.println(ret); }

  

java后端模拟表单提交的更多相关文章

  1. HTTP通信模拟表单提交数据

    前面记录过一篇关于http通信,发送数据的文章:http://www.cnblogs.com/hyyq/p/7089040.html,今天要记录的是如何通过http模拟表单提交数据. 一.通过GET请 ...

  2. 使用axios模拟表单提交

    1.需求背景 最近在实验室写一个Spring前后端分离的项目,项目中使用Spring Security组件实现系统的认证和授权,当Security的认证模式设置为FormLogin时(如下代码),前端 ...

  3. 表单提交---前端页面模拟表单提交(form)

    有些时候我们的前端页面总没有<form></form>表单,但是具体的业务时,我们又必须用表单提交才能达到我们想要的结果,LZ最近做了一些关于导出的一些功能,需要调用浏览器默认 ...

  4. <记录> axios 模拟表单提交数据

    ajax 可以通过 FormData 对象模拟表单提交数据 第一种方式:自定义FormData信息 //创建formData对象 var formData = new FormData(); //添加 ...

  5. 项目总结15:JavaScript模拟表单提交(实现window.location.href-POST提交数据效果)

    JavaScript模拟表单提交(实现window.location.href-POST提交数据效果) 前沿 1-在具体项目开发中,用window.location.href方法下载文件,因windo ...

  6. 由于想要实现下载的文件可以进行选择,而不是通过<a>标签写死下载文件的参数,所以一直想要使用JFinal结合ajax实现文件下载,但是ajax实现的文件下载并不能触发浏览器的下载文件弹出框,这里通过模拟表单提交实现同样的效果。

    由于想要实现下载的文件可以进行选择,而不是通过<a>标签写死下载文件的参数,所以一直想要使用JFinal结合ajax实现文件下载(这样的话ajax可以传递不同的参数),但是ajax实现的文 ...

  7. 利用HttpWebRequest模拟表单提交 JQuery 的一个轻量级 Guid 字符串拓展插件. 轻量级Config文件AppSettings节点编辑帮助类

    利用HttpWebRequest模拟表单提交   1 using System; 2 using System.Collections.Specialized; 3 using System.IO; ...

  8. C# Winform利用POST传值方式模拟表单提交数据(Winform与网页交互)

    其原理是,利用winfrom模拟表单提交数据.将要提交的參数提交给网页,网页运行代码.得到数据.然后Winform程序将网页的全部源码读取下来.这样就达到windows应用程序和web应用程序之间传參 ...

  9. c# 模拟表单提交,post form 上传文件、大数据内容

    表单提交协议规定:要先将 HTTP 要求的 Content-Type 设为 multipart/form-data,而且要设定一个 boundary 参数,这个参数是由应用程序自行产生,它会用来识别每 ...

随机推荐

  1. bzoj1036: [ZJOI2008]树的统计Count 树链剖分+线段树

    入门题 + 熟悉代码 /************************************************************** Problem: 1036 User: 96655 ...

  2. hdu 4720 计算几何简单题

    昨天用vim练了一道大水题,今天特地找了道稍难一点的题.不过也不是很难,简单的计算几何而已.练习用vim编码,用gdb调试,结果居然1A了,没调试...囧... 做法很简单,无非就是两种情况:①三个巫 ...

  3. 一幅图概括Android测试的方方面面

    一幅图概括Android测试的方方面面,来自网络: 另外的一些测试技巧 1,测试应用程序时,环境是很大的一个影响因素:系统时间,网络情况,异常关闭等 2,测试应用程序时,第三方嵌入程序也是有影响的.如 ...

  4. Nginx + PHP 缓存详解

    Nginx缓存nginx有两种缓存机制:fastcgi_cache和proxy_cache下面我们来说说这两种缓存机制的区别吧proxy_cache作用是缓存后端服务器的内容,可能是任何内容,包括静态 ...

  5. 基于MFC和opencv的FFT

    在网上折腾了一阵子,终于把这个程序写好了,程序是基于MFC的,图像显示的部分和获取图像的像素点是用到了opencv的一些函数,不过FFT算法没有用opencv的(呵呵,老师不让),网上的二维的FFT程 ...

  6. 使用rpmbuild来创建自己的RPM

    1. 进行创建必须的目录 在6.2的版本中,路径发生了变化,必须在此路径中,否则必须要修改配置文件. 2. 创建脚本文件 编写一个简单的脚本,然后将脚本进行打包为tar.gz格式的压缩文件,并且将其放 ...

  7. UIButton 在 iOS7.0与iOS7.1 中关于enabled的一点区别

    前些日子,在一台iOS7.0的设备上进行调试,关于UIButton的一部分代码如下 1 self.btn_loadmore.enabled = NO; 2 [self.btn_loadmore set ...

  8. SQL Server 跨库连接

    -- 开启组件 reconfigure reconfigure -- 关闭组件 reconfigure reconfigure -- 查询远程数据库 SELECT * FROM OPENDATASOU ...

  9. log4j2使用总结

    一.Log4j有三个主要的组件:Loggers,Appenders和Layouts,这里可简单理解为日志级别,日志要输出的地方和日志格式 1. Logger Logger的日志级别有6级,分别是TRA ...

  10. 07 java main方法

    1.问题:Java main方法为什么是  public static void main(String[] args)??? 序号 场景 编译 运行 解释 1 public修改为private pr ...