java发送url请求进行文件的提交以及后台struts2的action接收处理

java发送url请求进行文件的提交以及后台struts2的action接收处理

1、java模拟表单方式发送url请求进行文件的提交

[java]  view plain copy
  1. /** 
  2.  *  
  3.  * @作者 王建明 
  4.  * @创建日期 2013-06-27 
  5.  * @创建时间 19:28:18 
  6.  * @描述 —— 模拟表单进行文件数据提交 
  7.  */  
  8. private static void testSimulateFormToPostFile() {  
  9.     String localPath = "F:\\软件开发经验\\DeleteNullDir.java";  
  10.     File file = null;// 本地文件  
  11.     URL url = null;// 服务器action地址  
  12.     StringBuffer sb_cookie = null;// 拼装cookies  
  13.     StringBuffer sb_body = null;// 报文体  
  14.     HttpURLConnection httpUrl = null;// http协议类  
  15.     OutputStream fos = null;// 文件流  
  16.     FileInputStream fis = null;// 服务器回写响应流  
  17.     BufferedReader br = null;// 读取响应  
  18.     try {  
  19.         file = new File(localPath);  
  20.         if (!file.exists()) {  
  21.             throw new Exception();  
  22.         }  
  23.         String _url = "http://10.49.61.101:9999/finance/ajaxUploadFile.do";  
  24.         // Cookie[] cs = request.getCookies();  
  25.         // sb_cookie = new StringBuffer();  
  26.         // for (Cookie c : cs) {  
  27.         // sb_cookie.append(" ");  
  28.         // sb_cookie.append(c.getName());  
  29.         // sb_cookie.append("=");  
  30.         // sb_cookie.append(c.getValue());  
  31.         // sb_cookie.append(";");  
  32.         // }  
  33.         // String cookie = sb_cookie.substring(0, sb_cookie.length() - 1);//  
  34.         // cookie结束不含有";"  
  35.         String boundary = "---------------------------7da2e536604c8";  
  36.         url = new URL(_url);  
  37.         httpUrl = (HttpURLConnection) url.openConnection();// 创建连接  
  38.         httpUrl.setDoInput(true);// 创建输入流,必须有  
  39.         httpUrl.setDoOutput(true);// 创建输出流,必须有  
  40.         httpUrl.setUseCaches(false);// 不缓存  
  41.         httpUrl.setConnectTimeout(30000);// 连接超时  
  42.         httpUrl.setReadTimeout(30000);// 响应超时  
  43.         httpUrl.setRequestMethod("POST");  
  44.         httpUrl.setRequestProperty("Content-Length""" + file.length());// 文件大小  
  45.         httpUrl.addRequestProperty("Charset""UTF-8");  
  46.         httpUrl.addRequestProperty("Content-Type",  
  47.                 "multipart/form-data;boundary=" + boundary);  
  48.         httpUrl.addRequestProperty("Connection""Keep-Alive");// 连接方式,此处为长连接  
  49.         // httpUrl.addRequestProperty("Cookie", cookie);// 权限验证使用  
  50.         fos = httpUrl.getOutputStream();  
  51.         // 注意,http协议,是流传输,全部内容都要转换为byte类型  
  52.         sb_body = new StringBuffer();  
  53.         // 分隔符  
  54.         sb_body.append("--");  
  55.         sb_body.append(boundary);  
  56.         sb_body.append("\r\n");  
  57.         // 文档类型  
  58.         sb_body.append("Content-Disposition: form-data;name=\"upFile\";"  
  59.                 + "filename=\"" + "upload_data.xlsx" + "\"\r\n");  
  60.         sb_body.append("Content-Type:application/ms-word\r\n\r\n");  
  61.         byte[] head = sb_body.toString().getBytes();  
  62.         fos.write(head);  
  63.         // 文件内容  
  64.         fis = new FileInputStream(file);  
  65.         byte[] read = new byte[2048];  
  66.         int offset = 0;  
  67.         while ((offset = fis.read(read)) != -1) {  
  68.             fos.write(read, 0, offset);  
  69.         }  
  70.         fos.write(("\r\n--" + boundary + "--\r\n").getBytes());  
  71.         fos.flush();// 发送请求  
  72.         // HTTP响应  
  73.         br = new BufferedReader(new InputStreamReader(httpUrl  
  74.                 .getInputStream()));  
  75.         String line = null;  
  76.         StringBuffer sb = new StringBuffer();  
  77.         while ((line = br.readLine()) != null) {  
  78.             sb.append(line);  
  79.         }  
  80.         System.out.println(sb.toString());  
  81.     } catch (Exception e) {  
  82.         e.printStackTrace();  
  83.     }  
  84. }  

2、java使用流的方式发送url请求进行文件的提交

[java]  view plain copy
  1. /** 
  2.  *  
  3.  * @作者 王建明 
  4.  * @创建日期 2013-06-27 
  5.  * @创建时间 19:30:05 
  6.  * @描述 —— 将文件流直接post的方式进行文件的提交 
  7.  */  
  8. private static void testPostInStream() {  
  9.     try {  
  10.         URL url = new URL(  
  11.                 "http://10.49.61.101:9999/finance/ajaxUploadFileTwo.do?filePath=/c/v/b/&fileName=aaa.xlsx");  
  12.         // 发送POST请求必须设置如下两行  
  13.         HttpURLConnection conn = (HttpURLConnection) url.openConnection();  
  14.   
  15.         conn.setDoOutput(true);  
  16.         conn.setUseCaches(false);  
  17.         conn.setRequestMethod("POST");  
  18.         conn.setRequestProperty("Content-Type""text/html");  
  19.         conn.setRequestProperty("Cache-Control""no-cache");  
  20.         conn.setRequestProperty("Charsert""UTF-8");  
  21.         // conn.setRequestProperty("upFileFileName", "upFileFileName.doc");  
  22.         conn.connect();  
  23.         conn.setConnectTimeout(10000);  
  24.   
  25.         OutputStream out = conn.getOutputStream();  
  26.   
  27.         File file = new File("F:\\软件开发经验\\NumberFormateUtil.java");  
  28.   
  29.         DataInputStream in = new DataInputStream(new FileInputStream(file));  
  30.   
  31.         int bytes = 0;  
  32.         byte[] buffer = new byte[1024];  
  33.         while ((bytes = in.read(buffer)) != -1) {  
  34.             out.write(buffer, 0, bytes);  
  35.         }  
  36.         in.close();  
  37.         out.flush();  
  38.         out.close();  
  39.   
  40.         BufferedReader br = new BufferedReader(new InputStreamReader(conn  
  41.                 .getInputStream()));  
  42.         String line = null;  
  43.         StringBuffer sb = new StringBuffer();  
  44.         while ((line = br.readLine()) != null) {  
  45.             sb.append(line);  
  46.         }  
  47.         System.out.println(sb.toString());  
  48.         conn.disconnect();  
  49.         System.out.println("over");  
  50.     } catch (Exception e) {  
  51.         System.out.println("发送文件出现异常!" + e);  
  52.         e.printStackTrace();  
  53.     }  
  54. }  

3、后台服务端对应的struts2进行文件内容的接收处理【ajaxUploadFile和ajaxUploadFileTwo两个action的接收处理】

[java]  view plain copy
  1. package com.eshopmates.finance.action;  
  2.   
  3. import java.io.File;  
  4. import java.io.FileOutputStream;  
  5. import java.io.IOException;  
  6. import java.io.InputStream;  
  7.   
  8. import javax.servlet.http.HttpServletRequest;  
  9.   
  10. import org.apache.commons.io.FileUtils;  
  11. import org.apache.struts2.ServletActionContext;  
  12.   
  13. import com.opensymphony.xwork2.Action;  
  14.   
  15. /** 
  16.  * @作者 王建明 
  17.  * @创建日期 2013-06-27 
  18.  * @创建时间 18:22:33 
  19.  * @版本号 V 1.0 
  20.  */  
  21. public class GetPostFileAction extends BaseAction {  
  22.     // 上传文件  
  23.     private File upFile;// 拦截器会为你在缓冲区创建临时文件,这是临时文件对象  
  24.     private String upFileContentType;// 头域中的值  
  25.     private String upFileFileName;// 报文体中的name  
  26.   
  27.     /** 
  28.      * @return 
  29.      * @作者 王建明 
  30.      * @创建日期 2013-06-27 
  31.      * @创建时间 19:26:22 
  32.      * @描述 —— 网页表单方式或者模拟表单方式提交file文件进行处理 
  33.      */  
  34.     @org.apache.struts2.convention.annotation.Action("ajaxUploadFile")  
  35.     public String ajaxUploadFile() {  
  36.         String result;  
  37.         try {  
  38.             String path = getRequest().getSession().getServletContext()  
  39.                     .getRealPath("/uploadFile/" + upFileFileName);// 绝对路径  
  40.             File currFile = new File(path);  
  41.             System.out  
  42.                     .println("接收到的文件存放路径======>" + currFile.getAbsolutePath());  
  43.             FileUtils.copyFile(this.upFile, currFile);// struts2提供的工具类,意思是把缓存区文件放到哪里  
  44.             result = "{\"success\":true,\"uploadFile\":\"" + currFile.getAbsolutePath()  
  45.                     + "\",\"fileSize\":" + currFile.length() + "}";  
  46.         } catch (IOException e) {  
  47.             e.printStackTrace();  
  48.             result = "{\"success\":false}";  
  49.         }  
  50.         super.ajaxPrintMsg(result, super.CONTENTTYPE_HTML);  
  51.         System.out.println("result========>" + result);  
  52.         return Action.NONE;  
  53.     }  
  54.   
  55.     /** 
  56.      * @return 
  57.      * @throws Exception 
  58.      * @作者 王建明 
  59.      * @创建日期 2013-06-27 
  60.      * @创建时间 19:26:55 
  61.      * @描述 —— 直接以文件流的形式进行文件的post提交 
  62.      */  
  63.     @org.apache.struts2.convention.annotation.Action("ajaxUploadFileTwo")  
  64.     public String ajaxUploadFileTwo() throws Exception {  
  65.         String result;  
  66.         HttpServletRequest request = ServletActionContext.getRequest();  
  67.         String rootPath = request.getSession().getServletContext().getRealPath(  
  68.                 "/");  
  69.   
  70.         String filePath = request.getParameter("filePath");  
  71.         String fileName = request.getParameter("fileName");  
  72.         System.out.println("fileName=====>" + fileName);  
  73.   
  74.         InputStream input = request.getInputStream();  
  75.         String fileFullPath = rootPath + filePath + fileName;  
  76.         File saveFile = new File(fileFullPath);  
  77.   
  78.         File file = new File(rootPath + filePath);  
  79.         if (!file.exists()) {  
  80.             file.mkdirs();  
  81.         }  
  82.         FileOutputStream fos = new FileOutputStream(fileFullPath);  
  83.   
  84.         int size = 0;  
  85.         byte[] buffer = new byte[1024];  
  86.         while ((size = input.read(buffer, 01024)) != -1) {  
  87.             fos.write(buffer, 0, size);  
  88.         }  
  89.         fos.close();  
  90.         input.close();  
  91.         result = "{\"success\":true,\"uploadFileName\":\""  
  92.                 + saveFile.getAbsolutePath() + "\",\"fileSize\":"  
  93.                 + saveFile.length() + "}";  
  94.         super.ajaxPrintMsg(result, super.CONTENTTYPE_HTML);  
  95.         System.out.println("filePath===>" + file.getAbsolutePath());  
  96.         return Action.NONE;  
  97.     }  
  98.   
  99.     public File getUpFile() {  
  100.         return upFile;  
  101.     }  
  102.   
  103.     public void setUpFile(File upFile) {  
  104.         this.upFile = upFile;  
  105.     }  
  106.   
  107.     public String getUpFileContentType() {  
  108.         return upFileContentType;  
  109.     }  
  110.   
  111.     public void setUpFileContentType(String upFileContentType) {  
  112.         this.upFileContentType = upFileContentType;  
  113.     }  
  114.   
  115.     public String getUpFileFileName() {  
  116.         return upFileFileName;  
  117.     }  
  118.   
  119.     public void setUpFileFileName(String upFileFileName) {  
  120.         this.upFileFileName = upFileFileName;  
  121.     }  
  122. }  
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值