转自:http://blog.csdn.net/5iasp/article/details/8669644

模拟表单html如下:

 
<form action="up_result.jsp" method="post" enctype="multipart/form-data" name="form1" id="form1">
 
    <label>
  <input type="text" name="name" value="" />
  </label>
  
    <label>
  <input type="file" name="userfile" />
  </label>
  
  <label>
  <input type="submit" value="上传" />
  </label>
</form>
 
 
java代码如下:
 
[java] view plain copy
package com.yanek.util;  
  
import java.io.BufferedReader;  
import java.io.DataInputStream;  
import java.io.DataOutputStream;  
import java.io.File;  
import java.io.FileInputStream;  
import java.io.InputStreamReader;  
import java.io.OutputStream;  
import java.net.HttpURLConnection;  
import java.net.URL;  
import java.util.HashMap;  
import java.util.Iterator;  
import java.util.Map;  
  
import javax.activation.MimetypesFileTypeMap;  
  
import net.sf.json.JSONArray;  
import net.sf.json.JSONObject;  
  
public class HttpPostUploadUtil {  
  
    /** 
     * @param args 
     */  
    public static void main(String[] args) {  
          
        String filepath="E:\\ziliao\\0.jpg";  
          
        String urlStr = "http://127.0.0.1:8080/minicms/up/up_result.jsp";  
          
        Map<String, String> textMap = new HashMap<String, String>();  
      
        textMap.put("name", "testname");  
  
        Map<String, String> fileMap = new HashMap<String, String>();  
          
        fileMap.put("file", filepath);  
          
        String ret = formUpload(urlStr, textMap, fileMap);  
          
        System.out.println(ret);  
          
  
    }  
      
      
  
    /** 
     * 上传图片 
     *  
     * @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;  
    }  
  
}

java模拟post方式提交表单实现图片上传【转】的更多相关文章

  1. java模拟表单上传文件,java通过模拟post方式提交表单实现图片上传功能实例

    java模拟表单上传文件,java通过模拟post方式提交表单实现图片上传功能实例HttpClient 测试类,提供get post方法实例 package com.zdz.httpclient; i ...

  2. 4 django系列之HTML通过form标签来同时提交表单内容与上传文件

    preface 我们知道提交表单有2种方式,一种直接通过submit页面刷新方法来提交,另一种通过ajax异步局部刷新的方法提交,上回我们说了通过ajax来提交文件到后台,现在说说通过submit来提 ...

  3. php使用jquery Form ajax 提交表单,并上传文件

    在html5中我们通过FormData就可以ajax上传文件数据,不过因为兼容问题.我们选用jquery.form.min.js来进行ajax的表单提交.   一.jquery.form.js下载地址 ...

  4. ajax提交表单,支持文件上传

    当我们提交表单但是又不想要刷新页面的时候就可以考虑使用ajax来实现提交功能,但是这有个局限就是当有文件上传的时候是行不通的,下面借助于jquery.form可以很方便满足我们的需求.   1.表单写 ...

  5. SpringMVC(十四):SpringMVC 与表单提交(post/put/delete的用法);form属性设置encrypt='mutilpart/form-data'时,如何正确配置web.xml才能以put方式提交表单

    SpringMVC 与表单提交(post/put/delete的用法) 为了迎合Restful风格,提供的接口可能会包含:put.delete提交方式.在springmvc中实现表单以put.dele ...

  6. [原创]java WEB学习笔记49:文件上传基础,基于表单的文件上传,使用fileuoload 组件

    本博客为原创:综合 尚硅谷(http://www.atguigu.com)的系统教程(深表感谢)和 网络上的现有资源(博客,文档,图书等),资源的出处我会标明 本博客的目的:①总结自己的学习过程,相当 ...

  7. Struts2文件上传(基于表单的文件上传)

    •Commons-FileUpload组件 –Commons是Apache开放源代码组织的一个Java子项目,其中的FileUpload是用来处理HTTP文件上传的子项目   •Commons-Fil ...

  8. Django框架 之 Form表单和Ajax上传文件

    Django框架 之 Form表单和Ajax上传文件 浏览目录 Form表单上传文件 Ajax上传文件 伪造Ajax上传文件 Form表单上传文件 html 1 2 3 4 5 6 7 <h3& ...

  9. php前台表单限制PHP上传大小

    在php文件上传时候,一般我都认为考虑php.ini配置修改文件上传大小,还后台控制上传大小,这里教你php前台表单限制PHP上传大小 <form action="http://www ...

随机推荐

  1. [LeetCode] Customers Who Never Order 从未下单订购的顾客

    Suppose that a website contains two tables, the Customers table and the Orders table. Write a SQL qu ...

  2. [LeetCode] Remove Duplicates from Sorted List 移除有序链表中的重复项

    Given a sorted linked list, delete all duplicates such that each element appear only once. For examp ...

  3. NDT(Normal Distribution Transform) 算法(与ICP对比)和一些常见配准算法

    原文地址:http://ghx0x0.github.io/2014/12/30/NDT-match/ By GH 发表于 12月 30 2014 目前三维配准中用的较多的是ICP迭代算法,需要提供一个 ...

  4. js实现可拖动Div

    随着时代的变化,越来越感觉到js的重要性,js不仅可以做web页面(如Ext框架),还可以做一些web的特效,这些特效不仅兼容PC,而且兼容手机端,毕竟是基于浏览器的,和平台没关系.现在微软的wind ...

  5. hihocoder-1014 Trie树

    hihocoder 1014 : Trie树 link: https://hihocoder.com/problemset/problem/1014 题意: 实现Trie树,实现对单词的快速统计. # ...

  6. SSH框架的简单上传功能的实现

    1.创建项目. 2.导入开发包. 3.配置web.xml. 配置内容就是配置struct2的内容如下: <?xml version="1.0" encoding=" ...

  7. 精通Web Analytics 2.0 (11) 第九章: 新兴分析—社交,移动和视频

    精通Web Analytics 2.0 : 用户中心科学与在线统计艺术 第九章: 新兴分析-社交,移动和视频 网络在过去几年中发生了不可思议的发展变化:从单向对话到双向对话的转变; 由视频,Ajax和 ...

  8. 渗透测试-信息收集-c段收集

    平时做渗透测试我比较喜欢用lijiejie 写的 subDomainsBrute来爆破子域名 那么爆破完成后就想收集一下网站的c段信息 下面以平安为例 爆破得到子域名为 i.pingan.com.cn ...

  9. Bzoj3450 Tyvj1952 Easy

    Time Limit: 10 Sec  Memory Limit: 128 MBSubmit: 570  Solved: 428[Submit][Status][Discuss] Descriptio ...

  10. JavaScript系列文章:详解正则表达式之一

    正则表达式是一个精巧的利器,经常用来在字符串中查找和替换,JavaScript语言参照Perl,也提供了正则表达式相关模块,开发当中非常实用,在一些类库或是框架中,比如jQuery,就存在大量的正则表 ...