咱們先來看一下用html寫簡單的表單(form)是什麼樣的,以下: html
- <html>
- <head>
- <title>上傳文件測試頁面</title>
- <meta http-equiv="Content-Type" content="text/html; charset=UTF-8"/>
- </head>
- <body>
- <form method="post" action="http://your_address" enctype="multipart/form-data">
- <input type='hidden' id="do" name="do" value="justDoIt"/>
- <fieldset>
- <label> 名稱:</label><input type='text' id='myname' name='myname' size='35' maxlength='255'><br/>
- <label>上傳文件:</label><input type='file' id='uploadFile' name="uploadFile" size='35' maxlength='255'><br/>
- <label>描述:</label><br/>
- <textarea rows="5" cols="100" id='description' name='description' >
- </fieldset>
- <fieldset>
- <input type='submit' id='submit'/>
- <input type='reset' id='reset'/>
- </fieldset>
- </form>
- </body>
- </html>
假設服務器都作好的狀況下,咱們點擊"提交",就能完成文件上傳工作。 java
需求: 數組
用java 模擬html表單(form)提交數據 包含多文件 上傳 表單提交。 服務器
不用多說,碼農的風格直接上代碼,說明全在代碼上了,用法參見main方法s app
- import java.io.ByteArrayOutputStream;
- import java.io.DataInputStream;
- import java.io.File;
- import java.io.FileInputStream;
- import java.io.FileNotFoundException;
- import java.io.FileOutputStream;
- import java.io.InputStream;
- import java.io.OutputStream;
- import java.util.ArrayList;
- import java.util.Enumeration;
- import java.util.Hashtable;
- import java.util.List;
-
- import java.net.HttpURLConnection;
- import java.net.URL;
-
- /**
- * 模擬html表單提交數據,喜歡研究的同窗能夠把代碼優化一下。
- */
- public class HttpMultipartRequest {
- //每一個post參數之間的分隔
- static final String BOUNDARY = "----------V2ymHFg03ehbqgZCaKO6jy";
-
- public static void main(String[] args) {
-
- List<String[]> stringParams = new ArrayList<String[]>();
- stringParams.add(new String[]{"do", "justDoIt"});
- stringParams.add(new String[]{"myname", "aa我是一個測試cc123"});
- stringParams.add(new String[]{"description", "bb我是碼農我是一個測試我是一個測試cc567"});
-
- List<String[]> fileParams = new ArrayList<String[]>();
- fileParams.add(new String[]{"uploadFile", "我是碼農的一個測試.zip", "application/zip", "D://我是一個測試.zip"});
- HttpMultipartRequest req = new HttpMultipartRequest("http://your_address", stringParams, fileParams);
- try {
- byte[] response = req.sendPost();
- System.out.println(new String(response));
- } catch (Exception e) {
- e.printStackTrace();
- }
-
- }
-
- // 鏈接的地址
- private String urlStr;
- // 文字post項集 strParams 1:key 2:value
- private List<String[]> strParams;
- // 文件的post項集 fileParams 1:fileField, 2.fileName, 3.fileType, 4.filePath
- private List<String[]> fileParams;
-
- /**
- * 創建一個request鏈接
- * @param urlStr
- * @param strParams 1:key 2:value
- * @param fileParams 1:fileField, 2.fileName, 3.fileType, 4.filePath
- */
- public HttpMultipartRequest(String urlStr, List<String[]> strParams, List<String[]> fileParams) {
- this.urlStr = urlStr;
- this.strParams = strParams;
- this.fileParams = fileParams;
-
- }
-
- /**
- * 向服務器發送post請求
- * @return byte[]
- * @throws Exception
- */
- public byte[] sendPost() throws Exception {
- //http鏈接器
- HttpURLConnection hc = null;
- //byte輸出流,用來讀取服務器返回的信息
- ByteArrayOutputStream bos = null;
- //輸入流,用來讀取服務器返回的信息
- InputStream is = null;
- //保存服務器返回的信息的byte數組
- byte[] res = null;
-
- try {
- URL url = new URL(urlStr);
- hc = (HttpURLConnection) url.openConnection();
-
- hc.setRequestProperty("Content-Type", "multipart/form-data; boundary=" + BOUNDARY);
- hc.setRequestProperty("Charsert", "UTF-8");
- // 發送POST請求必須設置以下兩行
- hc.setDoOutput(true);
- hc.setDoInput(true);
- hc.setUseCaches(false);
- hc.setRequestMethod("POST");
-
- OutputStream dout = hc.getOutputStream();
- ////1.先寫文字形式的post流
- //頭
- String boundary = BOUNDARY;
- //中
- StringBuffer resSB = new StringBuffer("/r/n");
- //尾
- String endBoundary = "/r/n--" + boundary + "--/r/n";
- //strParams 1:key 2:value
- if(strParams != null){
- for(String[] parsm : strParams){
- String key = parsm[0];
- String value = parsm[1];
- resSB.append("Content-Disposition: form-data; name=/"").append(key).append("/"/r/n").append("/r/n").append(
- value).append("/r/n").append("--").append(boundary).append("/r/n");
- }
- }
- String boundaryMessage = resSB.toString();
-
- //寫出流
- dout.write( ("--"+boundary+boundaryMessage).getBytes("utf-8") );
-
- //2.再寫文件開式的post流
- //fileParams 1:fileField, 2.fileName, 3.fileType, 4.filePath
- resSB = new StringBuffer();
- if(fileParams != null){
- for(int i=0, num=fileParams.size(); i<num; i++){
- String[] parsm = fileParams.get(i);
- String fileField = parsm[0];
- String fileName = parsm[1];
- String fileType = parsm[2];
- String filePath = parsm[3];
-
- resSB.append("Content-Disposition: form-data; name=/"").append(fileField).append("/"; filename=/"").append(
- fileName).append("/"/r/n").append("Content-Type: ").append(fileType).append("/r/n/r/n");
-
- dout.write( resSB.toString().getBytes("utf-8") );
-
- //開始寫文件
- File file = new File(filePath);
- DataInputStream in = new DataInputStream(new FileInputStream(file));
- int bytes = 0;
- byte[] bufferOut = new byte[1024 * 5];
- while ((bytes = in.read(bufferOut)) != -1) {
- dout.write(bufferOut, 0, bytes);
- }
-
- if(i<num-1){
- dout.write( endBoundary.getBytes("utf-8") );
- }
-
- in.close();
- }
-
- }
-
- //3.最後寫結尾
- dout.write( endBoundary.getBytes("utf-8") );
-
- dout.close();
-
- int ch;
-
- is = hc.getInputStream();
-
- bos = new ByteArrayOutputStream();
- while ((ch = is.read()) != -1) {
- bos.write(ch);
- }
- res = bos.toByteArray();
- } catch (Exception e) {
- e.printStackTrace();
- } finally {
- try {
- if (bos != null)
- bos.close();
-
- if (is != null)
- is.close();
-
- } catch (Exception e2) {
- e2.printStackTrace();
- }
- }
- return res;
- }
-
-
- }