应用程序模拟表单向Servlet传送属性和文件

原文参考地址 :http://blog.csdn.net/pathuang68/article/details/6920076

找了半天,找到上面的原文地址,然后试了试,发现word等生成了文件,但打不开。然后就发了一个.txt文件,发现文件最后多出了MIME的协议头。

发送文件的核心代码主要是HttpPostEmulator.java类,看了一下作者的写的格式,又参考了一下MIME的书写方式,改进了一下

HttpPostEmulator类:

import java.io.BufferedReader;
import java.io.DataInputStream;
import java.io.File;
import java.io.FileInputStream;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.OutputStream;
import java.net.HttpURLConnection;
import java.net.URL;
import java.util.ArrayList;

public class HttpPostEmulator {
	//每个post参数之间的分隔。随意设定,只要不会和其他的字符串重复即可。

    private static final String BOUNDARY ="----------HV2ymHFg03ehbqgZCaKO6jyH";
    public String sendHttpPostRequest(String serverUrl
    		,ArrayList<FormFieldKeyValuePair>generalFormFields,
    		ArrayList<UploadFileItem>filesToBeUploaded) throws Exception{
              // 向服务器发送post请求
              URL url = new URL(serverUrl/*"http://127.0.0.1:8080/test/upload"*/);
              HttpURLConnection connection= (HttpURLConnection) url.openConnection();           
              // 发送POST请求必须设置如下两行
              connection.setDoOutput(true);
              connection.setDoInput(true);
              connection.setUseCaches(false);
              connection.setRequestMethod("POST");
              connection.setRequestProperty("Connection","Keep-Alive");
              connection.setRequestProperty("Charset","UTF-8");
              connection.setRequestProperty("Content-Type","multipart/form-data; boundary=" + BOUNDARY);             

              // 头
              String boundary = BOUNDARY;
              boolean isParams = false;
              // 传输内容
              StringBuffer contentBody =new StringBuffer();
              // 尾
              String endBoundary ="\r\n--" + boundary + "--\r\n";          

              OutputStream out =connection.getOutputStream();          
              // 1. 处理普通表单域(即形如key = value对)的POST请求
              for(FormFieldKeyValuePair ffkvp : generalFormFields){
            	  	   isParams = true;
                       contentBody.append("--"+BOUNDARY).append("\r\n")
                      .append("Content-Disposition: form-data; name=\"")
                      .append(ffkvp.getKey() + "\"")
                      .append("\r\n")
                      .append("\r\n")
                      .append(ffkvp.getValue())
                      .append("\r\n");
              }
              //contentBody.append("\r\n");
              String boundaryMessage1 =contentBody.toString();
              if(isParams){
                 out.write(boundaryMessage1.getBytes("utf-8"));
              }

              // 2. 处理文件上传
              for(UploadFileItem ufi :filesToBeUploaded){
                       contentBody = new StringBuffer();
                       contentBody.append("--"+BOUNDARY).append("\r\n")
                     .append("Content-Disposition:form-data; name=\"")
                     .append(ufi.getFormFieldName() +"\"; ")   // form中field的名称
                     .append("filename=\"")
                     .append(ufi.getFileName() +"\"")   //上传文件的文件名,包括目录
                     .append("\r\n")
                     .append("Content-Type:application/octet-stream")
                     .append("\r\n\r\n");                      

                       String boundaryMessage2 = contentBody.toString();
                       out.write(boundaryMessage2.getBytes("utf-8"));                     

                       // 开始真正向服务器写文件
                       File file = new File(ufi.getFileName());
                       DataInputStream dis= new DataInputStream(new FileInputStream(file));
                       int bytes = 0;
                       byte[] bufferOut =new byte[(int) file.length()];
                       bytes =dis.read(bufferOut);
                       out.write(bufferOut,0, bytes);
                       dis.close();
                       
                       out.write("\r\n".getBytes("utf-8"));
                       
//                       contentBody.setLength(0);
//                       contentBody.append("--"+BOUNDARY).append("\r\n");                     
//
//                       String boundaryMessage = contentBody.toString();
//                       out.write(boundaryMessage.getBytes("utf-8"));
//                       System.out.println(boundaryMessage);
              }
              //out.write(("--"+ BOUNDARY + "--\r\n").getBytes("UTF-8"));            
              // 3. 写结尾
              out.write(endBoundary.getBytes("utf-8"));
              out.flush();
              out.close();            
              // 4. 从服务器获得回答的内容
              String strLine="";
              String strResponse ="";
              InputStream in =connection.getInputStream();
              BufferedReader reader = new BufferedReader(new InputStreamReader(in));
              while((strLine =reader.readLine()) != null){
                       strResponse +=strLine +"\n";
              }
              return strResponse;

    }
}
ClientPost类 

import java.util.ArrayList;
import java.util.HashMap;
import java.util.Iterator;

public class ClientPost {
    public static String sendForms(String servletURL,HashMap paramsMap,HashMap fileMap){
        ArrayList<FormFieldKeyValuePair> ffkvp = new ArrayList<FormFieldKeyValuePair>();
        if(paramsMap!=null){
        	Iterator iter = paramsMap.keySet().iterator();
        	while(iter.hasNext()){
        		String key = (String)iter.next();
        		String value = (String)paramsMap.get(key);
        		ffkvp.add(new FormFieldKeyValuePair(key, value));
        	}
        }
        
     // 设定要上传的文件。UploadFileItem见后面的代码
        ArrayList<UploadFileItem> ufi = new ArrayList<UploadFileItem>();
        if(fileMap!=null){
        	Iterator iter = fileMap.keySet().iterator();
        	while(iter.hasNext()){
        		String key = (String)iter.next();
        		String value = (String)fileMap.get(key);
        		//ufi.add(new UploadFileItem("upload1", "E:\\Asturias.mp3"));
        		ufi.add(new UploadFileItem(key, value));
        	}
        }
        String response = "";
        try{
        	HttpPostEmulator hpe = new HttpPostEmulator();
        	response =hpe.sendHttpPostRequest(servletURL, ffkvp, ufi);
        }catch(Exception ex){
        	System.out.println(ex.getMessage());
            response = ex.getMessage();
        }
        return response;
    }
}

UploadFileItem类

import java.io.Serializable;

public class UploadFileItem implements Serializable{
	private static final long serialVersionUID = 1L;
    // The form field name in a form used foruploading a file,
    // such as "upload1" in "<inputtype="file" name="upload1"/>"
    private String formFieldName;
    // File name to be uploaded, thefileName contains path,
    // such as "E:\\some_file.jpg"
    private String fileName;  
    public UploadFileItem(String formFieldName, String fileName){
              this.formFieldName =formFieldName;
              this.fileName = fileName;
    }
    public String getFormFieldName(){
              return formFieldName;
    }
    public void setFormFieldName(String formFieldName){
              this.formFieldName =formFieldName;
    }
    public String getFileName(){
              return fileName;
    }
    public void setFileName(String fileName){
              this.fileName = fileName;
    }
}


FormFieldKeyValuePair.java

import java.io.Serializable;

public class FormFieldKeyValuePair implements Serializable{
	 private static final long serialVersionUID = 1L;
     // The form field used for receivinguser's input,
     // such as "username" in "<inputtype="text" name="username"/>"
     private String key;
     // The value entered by user in thecorresponding form field,
     // such as "Patrick" the abovementioned formfield "username"
     private String value;
     public FormFieldKeyValuePair(String key, String value){
               this.key = key;
               this.value = value;
     }
     public String getKey(){
               return key;
     }
     public void setKey(String key){
               this.key = key;
     }
     public String getValue(){
               return value;
     }
     public void setValue(String value){
               this.value = value;
     }
}

ServerReceive类

import org.apache.commons.fileupload.FileItem;
import org.apache.commons.fileupload.disk.DiskFileItemFactory;
import org.apache.commons.fileupload.servlet.ServletFileUpload;

public class ServerReceive  extends HttpServlet{
	private static final long serialVersionUID = 1L; 
    @Override
    protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException{
         super.doGet(req, resp);
    }
    @SuppressWarnings({"unchecked", "deprecation" })
    @Override
    protected void doPost(HttpServletRequest req, HttpServletResponse resp)throws ServletException, IOException{      
         DiskFileItemFactory factory =new DiskFileItemFactory();
        //得到绝对文件夹路径,比如"D:\\Tomcat6\\webapps\\test\\upload"
        String path = req.getRealPath("/upload");        //临时文件夹路径
        String repositoryPath =req.getRealPath("/upload/temp");        
        // 设定临时文件夹为repositoryPath
        factory.setRepository(new File(repositoryPath)); 
        // 设定上传文件的阈值,如果上传文件大于1M,就可能在repository
        // 所代 表的文件夹中产生临时文件,否则直接在内存中进行处理
        factory.setSizeThreshold(1024* 1024);          
        //System.out.println("----"+ req.getContextPath());  // 得到相对文件夹路径,比如 "/test"           
        // 创建一个ServletFileUpload对象
        ServletFileUpload uploader =new ServletFileUpload(factory);
        try{
	            // 调用uploader中的parseRequest方法,可以获得请求中的相关内容,
	            // 即一个FileItem类型的ArrayList。FileItem是在
	            // org.apache.commons.fileupload中定义的,它可以代表一个文件,
	            // 也可以代表一个普通的form field
	            ArrayList<FileItem>list = (ArrayList<FileItem>)uploader.parseRequest(req);
	            System.out.println(list.size());
	            for(FileItem fileItem : list){
	                 if(fileItem.isFormField()){      // 如果是普通的form field
	                         String name = fileItem.getFieldName();
	                         String value = fileItem.getString();
	                         System.out.println(name+ " = " + value);
	                  } else {  // 如果是文件
	                         String value = fileItem.getName();
	                         int start = value.lastIndexOf("\\");
	                         String fileName = value.substring(start + 1);
	                         // 将其中包含的内容写到path(即upload目录)下,
	                          // 名为fileName的文件中
	                         fileItem.write(new File(path, fileName));
	                  }
	             }
             }catch(Exception e) {
                       e.printStackTrace();
             }
             // 向客户端反馈结果
             PrintWriter out =resp.getWriter();
             out.print("OK");
             out.flush();
             out.close();            
             super.doPost(req, resp);
    }
}


调用入口

private String uploadFiles(HttpServletRequest request){
    	try{
	    	HashMap fileMap = new HashMap();
	    	String filePath = this.getClass().getClassLoader().getResource("/").toURI().getPath();
			String webRoot=filePath.substring(0,filePath.indexOf("WEB-INF"));
			filePath=webRoot+ "WEB-INF";
	    	fileMap.put("file1", filePath + "\\test.docx");
	    	fileMap.put("file2", filePath + "\\test.txt");
	    	
	    	HashMap paramMap = new HashMap();
	    	paramMap.put("userid", "111111"); 
	    	paramMap.put("username", "danielinbiti"); 
	        
	    	String rtn = ClientPost.sendForms("http://localhost:8080/test/ServerReceive", paramMap, fileMap);
	    	return rtn;
    	}catch(Exception ex){
    		System.out.println(ex.getMessage());
    	}
    	return null;
    }

经过测试,多个属性和多种文件都可以支持了。

评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值