package dshui;
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;
/**
* HttpUploadFile模拟POST上传图片
*
* @author Administrator
*
*/
public class HttpUploadFile {
public static void main(String[] args) {
testUploadImage();
}
/**
* 测试上传图片
*/
public static void testUploadImage() {
String url = "http://127.0.0.1/uploadImage.do";
String fileName = "C:/Users/Administrator/Desktop/image/1.jpg";
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 = "";// 上传类型,可为空
String ret = formUpload(url, textMap, fileMap, contentType);
System.out.println(ret);
}
/**
* 上传图片
*
* @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(
HttpUploadFile模拟前台POST上传图片和后台获取上传图片并上传至服务器
最新推荐文章于 2024-09-27 15:11:01 发布
本文介绍如何使用HttpUploadFile模拟前端POST方式上传图片文件,并详细阐述后台如何接收并处理这些上传的图片,最后将图片上传至远程服务器进行存储。
摘要由CSDN通过智能技术生成