1. 程式人生 > >java模擬表單上傳檔案,java通過模擬post方式提交表單實現圖片上傳功能例項

java模擬表單上傳檔案,java通過模擬post方式提交表單實現圖片上傳功能例項

package com.zdz.httpclient;


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;


/**
 * java通過模擬post方式提交表單實現圖片上傳功能例項
 * 其他檔案型別可以傳入 contentType 實現
 * @author zdz8207
 * {@link http://www.cnblogs.com/zdz8207/}
 * @version 1.0
 */
public class HttpUploadFile {


    public static void main(String[] args) {
        testUploadImage();
    }
    
    /**
     * 測試上傳png圖片
     * 
     */
    public static void testUploadImage(){
        String url = "http://xxx/wnwapi/index.php/Api/Index/testUploadModelBaking";
        String fileName = "e:/chenjichao/textures/antimap_0017.png";
        Map<String, String> textMap = new HashMap<String, String>();
        //可以設定多個input的name,value
        textMap.put("name", "testname");
        textMap.put("type", "2");
        //設定file的name,路徑
        Map<String, String> fileMap = new HashMap<String, String>();
        fileMap.put("upfile", fileName);
        String contentType = "";//image/png
        String ret = formUpload(url, textMap, fileMap,contentType);
        System.out.println(ret);
        //{"status":"0","message":"add succeed","baking_url":"group1\/M00\/00\/A8\/CgACJ1Zo-LuAN207AAQA3nlGY5k151.png"}
    }


    /**
     * 上傳圖片
     * @param urlStr
     * @param textMap
     * @param fileMap
     * @param contentType 沒有傳入檔案型別預設採用application/octet-stream
     * contentType非空採用filename匹配預設的圖片型別
     * @return 返回response資料
     */
    @SuppressWarnings("rawtypes")
    public static String formUpload(String urlStr, Map<String, String> textMap,
            Map<String, String> fileMap,String contentType) {
        String res = "";
        HttpURLConnection conn = null;
        // boundary就是request頭和上傳檔案內容的分隔符
        String BOUNDARY = "---------------------------123821742118716"; 
        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();
                    
                    //沒有傳入檔案型別,同時根據檔案獲取不到型別,預設採用application/octet-stream
                    contentType = new MimetypesFileTypeMap().getContentType(file);
                    //contentType非空採用filename匹配預設的圖片型別
                    if(!"".equals(contentType)){
                        if (filename.endsWith(".png")) {
                            contentType = "image/png"; 
                        }else if (filename.endsWith(".jpg") || filename.endsWith(".jpeg") || filename.endsWith(".jpe")) {
                            contentType = "image/jpeg";
                        }else if (filename.endsWith(".gif")) {
                            contentType = "image/gif";
                        }else if (filename.endsWith(".ico")) {
                            contentType = "image/image/x-icon";
                        }
                    }
                    if (contentType == null || "".equals(contentType)) {
                        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模擬檔案java通過模擬post方式提交實現圖片功能例項

package com.zdz.httpclient;import java.io.BufferedReader;import java.io.DataInputStream;import java.io.DataOutputStream;import java.io.File;import java.io.

java模擬post方式提交實現圖片

模擬表單html如下: <form action="up_result.jsp" method="post" enctype="multipart/form-data" name="form1" id="form1">       <label>

httpclient:與springmvc進行跨域傳輸檔案攜帶引數——使用HttpPost方式

一.上傳檔案1.HttpClient類/** * @param file * @param url */ public static void uploadFileByHttpPost(File file, String url) { CloseableHt

分散式檔案系統FastDFS簡介、搭建、與SpringBoot整合實現圖片

之前大學時搭建過一個FastDFS的圖片伺服器,當時只是抱著好奇的態度搭著玩一下,當時搭建採用了一臺虛擬機器,tracker和storage服務在一臺機器上放著,最近翻之前的部落格突然想著在兩臺機器上搭建試一下,順便整合了SpringBoot實現了一下圖片的上傳服務。 新的閱讀體驗地址:http://www

Java 通過HttpClient Post方式提交json並從服務端返回json資料

直接上程式碼吧,和前面幾篇文章都差不多 java程式碼: package PostPager; import java.io.IOException; import java.io.InputStream; import java.io.Output

Java 通過httpClient Post方式提交xml並從服務端返回資料

在通過http請求連線服務端程式時,有兩種方式httpClient這個不是標準的java庫,但是是開源專案,能夠快捷的開發,但如果做Android的開發,推薦使用httpUrlConnect這個工具。但是httpClient確實也是一個比較好用的工具。 這裡面

Java 通過HttpURLConnection Post方式提交json並從服務端返回json資料

這個技術和xml差不過,主要是服務端程式碼稍微修改,客戶端程式碼修改部分傳遞引數就可以完成,但在之前需要匯入json所需要的jar包。 PostJson.java程式碼 package PostPager; import java.io.InputSt

JavaScript 實現POST方式提交

        使用js實現POST表單提交主要應該在使用url資料提交時url地址超長的問題。 JavaScript程式碼如下: //Post方式提交表單 function PostSubmit(url, data, msg) { var postUrl = ur

使用httpclient模擬檔案後臺用struts2接收

本人是使用java,開發android後臺的,公司要求使用SSM框架,有一個功能要求是實現android大檔案的上傳。開發人員都是新手,以前沒有開發經驗,鼓搗了好久,也嘗試了兩個android框架,Xutils貌似跟struts2不太好整合,而AsyncHttpClient

form提交批量檔案不重新整理不跳轉頁面

jsp: <form action="inImg.do" method="post" enctype="multipart/form-data" target="nm_iframe"> <table> <tr>

使用HTML的form檔案需要考慮的幾個問題

應用系統中經常需要有檔案上傳功能,一般的做法都是使用HTML的<form>和<input type="file">,或者使用第三方檔案上傳元件,如swfupload和uploa

Java檔案:Restful介面接收檔案快取在本地

介面程式碼 import lombok.extern.slf4j.Slf4j; import org.springframework.web.bind.annotation.PostMapping; import org.springframework.web.bind.annotation.Requ

java、 http模擬post檔案到服務端 模擬form檔案

需求是這樣的: **1,前後端分離,前端對接pc軟體進行檔案同步的介面,後的springboot微服務進行檔案接收和處理。 2,軟體不能直接呼叫微服務的介面進行上傳,只能先走一下前端controller進行轉發過來()。 3,這樣就只能用httpclien

java檔案壓縮解壓儲存

<pre name="code" class="html">import java.io.BufferedInputStream; import java.io.BufferedOutputStream; import java.io.File; import

非同步檔案使用new FormData($(‘#uploadForm‘)[0])序列化

/// <summary>/// 上傳新圖片,(包含檔案上傳) /// </summary>/// <returns></returns>public JsonResult UpLoad() {

解決部署在Linux下的java程式檔案檔名中文亂碼

找了一圈資料,把centos的字符集、tomcat中server.xml中的“URIEncoding”都更改為UTF-8之後還是不成功。最終在tomcat/bin/catalina.sh檔案中增加了“export LANG=zh_CN.UTF-8”,成功解決了問題。

Javaweb----檔案excle表格錄入資料庫的

上傳檔案,excle表格錄入資料庫的表中 一開始遙望資料庫中錄入測試資料,但由於要做考試系統,所以用到了一個東西,那就是能不能把表格裡的東西錄入到資料庫中呢?經過仔細的研究,終於找到一種方式了。下面來

springMVC檔案MultipartHttpServletRequest、MultipartFile進行檔案

這裡使用apache的開源jar包完成上傳功能,使用jar包分別是:common-fileupload.jar和common-io.jar  先編寫上傳檔案幫助類,如果需要區分檔案型別,可以將檔案字尾擷取進行判斷; springmvc-mvc.xml配置,這裡主要配置spri

Qt Http QHttpMultiPart檔案java http伺服器

                         Qt Http QHttpMultiPart上傳檔案到java http伺服器 1.最近專案用到了Qt上傳檔案到HT

使用base64檔案後臺轉為MultipartFile

通常情況下,上傳檔案時,使用的都是file型別。我們再java後臺應用只需要使用MultipartFile接收就可以了。有的時候,或許我們也會遇到使用base64進行檔案上傳。今天,我們一起學習下後臺 應該如何處理這樣的情況。 由於MultipartFile的實現類都不太適用於base64的上傳