java发送url请求进行文件的提交以及后台struts2的action接收处理
1、java模拟表单方式发送url请求进行文件的提交
/**
*
* @作者 王建明
* @创建日期 2013-06-27
* @创建时间 19:28:18
* @描述 —— 模拟表单进行文件数据提交
*/
private static void testSimulateFormToPostFile() {
String localPath = "F:\\软件开发经验\\DeleteNullDir.java";
File file = null;// 本地文件
URL url = null;// 服务器action地址
StringBuffer sb_cookie = null;// 拼装cookies
StringBuffer sb_body = null;// 报文体
HttpURLConnection httpUrl = null;// http协议类
OutputStream fos = null;// 文件流
FileInputStream fis = null;// 服务器回写响应流
BufferedReader br = null;// 读取响应
try {
file = new File(localPath);
if (!file.exists()) {
throw new Exception();
}
String _url = "http://10.49.61.101:9999/finance/ajaxUploadFile.do";
// Cookie[] cs = request.getCookies();
// sb_cookie = new StringBuffer();
// for (Cookie c : cs) {
// sb_cookie.append(" ");
// sb_cookie.append(c.getName());
// sb_cookie.append("=");
// sb_cookie.append(c.getValue());
// sb_cookie.append(";");
// }
// String cookie = sb_cookie.substring(0, sb_cookie.length() - 1);//
// cookie结束不含有";"
String boundary = "---------------------------7da2e536604c8";
url = new URL(_url);
httpUrl = (HttpURLConnection) url.openConnection();// 创建连接
httpUrl.setDoInput(true);// 创建输入流,必须有
httpUrl.setDoOutput(true);// 创建输出流,必须有
httpUrl.setUseCaches(false);// 不缓存
httpUrl.setConnectTimeout(30000);// 连接超时
httpUrl.setReadTimeout(30000);// 响应超时
httpUrl.setRequestMethod("POST");
httpUrl.setRequestProperty("Content-Length", "" + file.length());// 文件大小
httpUrl.addRequestProperty("Charset", "UTF-8");
httpUrl.addRequestProperty("Content-Type",
"multipart/form-data;boundary=" + boundary);
httpUrl.addRequestProperty("Connection", "Keep-Alive");// 连接方式,此处为长连接
// httpUrl.addRequestProperty("Cookie", cookie);// 权限验证使用
fos = httpUrl.getOutputStream();
// 注意,http协议,是流传输,全部内容都要转换为byte类型
sb_body = new StringBuffer();
// 分隔符
sb_body.append("--");
sb_body.append(boundary);
sb_body.append("\r\n");
// 文档类型
sb_body.append("Content-Disposition: form-data;name=\"upFile\";"
+ "filename=\"" + "upload_data.xlsx" + "\"\r\n");
sb_body.append("Content-Type:application/ms-word\r\n\r\n");
byte[] head = sb_body.toString().getBytes();
fos.write(head);
// 文件内容
fis = new FileInputStream(file);
byte[] read = new byte[2048];
int offset = 0;
while ((offset = fis.read(read)) != -1) {
fos.write(read, 0, offset);
}
fos.write(("\r\n--" + boundary + "--\r\n").getBytes());
fos.flush();// 发送请求
// HTTP响应
br = new BufferedReader(new InputStreamReader(httpUrl
.getInputStream()));
String line = null;
StringBuffer sb = new StringBuffer();
while ((line = br.readLine()) != null) {
sb.append(line);
}
System.out.println(sb.toString());
} catch (Exception e) {
e.printStackTrace();
}
}
2、java使用流的方式发送url请求进行文件的提交
/**
*
* @作者 王建明
* @创建日期 2013-06-27
* @创建时间 19:30:05
* @描述 —— 将文件流直接post的方式进行文件的提交
*/
private static void testPostInStream() {
try {
URL url = new URL(
"http://10.49.61.101:9999/finance/ajaxUploadFileTwo.do?filePath=/c/v/b/&fileName=aaa.xlsx");
// 发送POST请求必须设置如下两行
HttpURLConnection conn = (HttpURLConnection) url.openConnection();
conn.setDoOutput(true);
conn.setUseCaches(false);
conn.setRequestMethod("POST");
conn.setRequestProperty("Content-Type", "text/html");
conn.setRequestProperty("Cache-Control", "no-cache");
conn.setRequestProperty("Charsert", "UTF-8");
// conn.setRequestProperty("upFileFileName", "upFileFileName.doc");
conn.connect();
conn.setConnectTimeout(10000);
OutputStream out = conn.getOutputStream();
File file = new File("F:\\软件开发经验\\NumberFormateUtil.java");
DataInputStream in = new DataInputStream(new FileInputStream(file));
int bytes = 0;
byte[] buffer = new byte[1024];
while ((bytes = in.read(buffer)) != -1) {
out.write(buffer, 0, bytes);
}
in.close();
out.flush();
out.close();
BufferedReader br = new BufferedReader(new InputStreamReader(conn
.getInputStream()));
String line = null;
StringBuffer sb = new StringBuffer();
while ((line = br.readLine()) != null) {
sb.append(line);
}
System.out.println(sb.toString());
conn.disconnect();
System.out.println("over");
} catch (Exception e) {
System.out.println("发送文件出现异常!" + e);
e.printStackTrace();
}
}
3、后台服务端对应的struts2进行文件内容的接收处理【ajaxUploadFile和ajaxUploadFileTwo两个action的接收处理】
package com.eshopmates.finance.action;
import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import javax.servlet.http.HttpServletRequest;
import org.apache.commons.io.FileUtils;
import org.apache.struts2.ServletActionContext;
import com.opensymphony.xwork2.Action;
/**
* @作者 王建明
* @创建日期 2013-06-27
* @创建时间 18:22:33
* @版本号 V 1.0
*/
public class GetPostFileAction extends BaseAction {
// 上传文件
private File upFile;// 拦截器会为你在缓冲区创建临时文件,这是临时文件对象
private String upFileContentType;// 头域中的值
private String upFileFileName;// 报文体中的name
/**
* @return
* @作者 王建明
* @创建日期 2013-06-27
* @创建时间 19:26:22
* @描述 —— 网页表单方式或者模拟表单方式提交file文件进行处理
*/
@org.apache.struts2.convention.annotation.Action("ajaxUploadFile")
public String ajaxUploadFile() {
String result;
try {
String path = getRequest().getSession().getServletContext()
.getRealPath("/uploadFile/" + upFileFileName);// 绝对路径
File currFile = new File(path);
System.out
.println("接收到的文件存放路径======>" + currFile.getAbsolutePath());
FileUtils.copyFile(this.upFile, currFile);// struts2提供的工具类,意思是把缓存区文件放到哪里
result = "{\"success\":true,\"uploadFile\":\"" + currFile.getAbsolutePath()
+ "\",\"fileSize\":" + currFile.length() + "}";
} catch (IOException e) {
e.printStackTrace();
result = "{\"success\":false}";
}
super.ajaxPrintMsg(result, super.CONTENTTYPE_HTML);
System.out.println("result========>" + result);
return Action.NONE;
}
/**
* @return
* @throws Exception
* @作者 王建明
* @创建日期 2013-06-27
* @创建时间 19:26:55
* @描述 —— 直接以文件流的形式进行文件的post提交
*/
@org.apache.struts2.convention.annotation.Action("ajaxUploadFileTwo")
public String ajaxUploadFileTwo() throws Exception {
String result;
HttpServletRequest request = ServletActionContext.getRequest();
String rootPath = request.getSession().getServletContext().getRealPath(
"/");
String filePath = request.getParameter("filePath");
String fileName = request.getParameter("fileName");
System.out.println("fileName=====>" + fileName);
InputStream input = request.getInputStream();
String fileFullPath = rootPath + filePath + fileName;
File saveFile = new File(fileFullPath);
File file = new File(rootPath + filePath);
if (!file.exists()) {
file.mkdirs();
}
FileOutputStream fos = new FileOutputStream(fileFullPath);
int size = 0;
byte[] buffer = new byte[1024];
while ((size = input.read(buffer, 0, 1024)) != -1) {
fos.write(buffer, 0, size);
}
fos.close();
input.close();
result = "{\"success\":true,\"uploadFileName\":\""
+ saveFile.getAbsolutePath() + "\",\"fileSize\":"
+ saveFile.length() + "}";
super.ajaxPrintMsg(result, super.CONTENTTYPE_HTML);
System.out.println("filePath===>" + file.getAbsolutePath());
return Action.NONE;
}
public File getUpFile() {
return upFile;
}
public void setUpFile(File upFile) {
this.upFile = upFile;
}
public String getUpFileContentType() {
return upFileContentType;
}
public void setUpFileContentType(String upFileContentType) {
this.upFileContentType = upFileContentType;
}
public String getUpFileFileName() {
return upFileFileName;
}
public void setUpFileFileName(String upFileFileName) {
this.upFileFileName = upFileFileName;
}
}