您的位置:首页 > 理论基础 > 计算机网络

HttpUploadFile模拟前台POST上传图片和后台获取上传图片并上传至服务器

2016-12-26 14:59 519 查看
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("\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:" + cont
f037
entType + "\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;
}
}


package com.iit.core.util;

import com.aliyun.oss.ClientException;
import com.aliyun.oss.OSSClient;
import com.aliyun.oss.OSSException;
import com.aliyun.oss.model.PutObjectRequest;
import com.dshui.oms.entity.Picture;
import com.iit.core.AppConfig;
import com.iit.core.Constants;
import com.iit.core.Convert;
import org.apache.commons.fileupload.FileItem;
import org.apache.commons.fileupload.FileUploadBase.SizeLimitExceededException;
import org.apache.commons.fileupload.FileUploadException;
import org.apache.commons.fileupload.disk.DiskFileItemFactory;
import org.apache.commons.fileupload.servlet.ServletFileUpload;

import javax.servlet.ServletException;
import javax.servlet.ServletOutputStream;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.File;
import java.io.IOException;
import java.util.Date;
import java.util.Iterator;
import java.util.List;
import java.util.UUID;

public class UploadImage extends HttpServlet {
private static final long serialVersionUID = 1L;

public static String getFilePath() {
return "file/" + Convert.toShortYMDWithNoSplit(new Date()) + "/";
}

protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
processRequest(request, response);
}

protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
processRequest(request, response);
}

private void processRequest(HttpServletRequest request, HttpServletResponse response) throws IOException {
response.setCharacterEncoding("UTF-8");
ServletOutputStream os = response.getOutputStream();

/*
*    oos需要的属性
* */

String endpoint = "http://oss-cn-beijing.aliyuncs.com";
String accessKeyId = "ytkBktFF0pPFRKh2";
String accessKeySecret = "EHOxUevFMBIxv6qBaVCT9pOcybZykt";
String bucketName = "goods-images";
OSSClient client = new OSSClient(endpoint, accessKeyId, accessKeySecret);

System.out.println(ServletFileUpload.isMultipartContent(request));

// 获得文件保存路径
/*  String filePath = getFilePath();
String path = getTempPath(filePath);
*/

// 临时文件目录
File temp = new File("/usr/local/temp/upload/");
if (!temp.exists())
temp.mkdirs();

// 实例化一个硬盘文件工厂,用来配置上传组件ServletFileUpload
DiskFileItemFactory factory = new DiskFileItemFactory(5 * 1024 * 1024, temp);
// 用以上工厂实例化上传组件
ServletFileUpload sfu = new ServletFileUpload(factory);
// 单个文件最大值
sfu.setSizeMax(5* 1024 * 1024);

List fileList = null;
try {
fileList = sfu.parseRequest(request);
} catch (FileUploadException e) {
if (e instanceof SizeLimitExceededException) {
os.write("文件太大了".getBytes("UTF-8"));
os.close();
return;
} else {
os.write("未知异常".getBytes("UTF-8"));
os.close();
return;
}
}

if (fileList == null || fileList.size() == 0) {
os.write("请上传文件".getBytes("UTF-8"));
os.close();
return;
}

String fileNames = null;
Iterator iter = fileList.iterator();
while (iter.hasNext()) {
FileItem item = (FileItem) iter.next();
if (!item.isFormField()) {
String fileName = item.getName();
if(fileName.lastIndexOf('.') == -1){
return;
}
String fileExt = fileName.substring(fileName.lastIndexOf('.'));
if (!Picture.ALLOW_EXT.contains(fileExt.toLowerCase())) {
os.write("文件类型错误".getBytes("UTF-8"));
os.close();
return;
}
fileName = getFileName() + fileExt;
try {
// 这里将图片上传到oos服务器上面服务器上面
File file = File.createTempFile(fileName, fileExt);
file.deleteOnExit();
item.write(file);
client.putObject(new PutObjectRequest(bucketName, fileName,file));
file.delete();

//item.write(new File(path, fileName));
} catch (OSSException oe) {
System.out.println("Caught an OSSException, which means your request made it to OSS, "
+ "but was rejected with an error response for some reason.");
System.out.println("Error Message: " + oe.getErrorCode());
System.out.println("Error Code:       " + oe.getErrorCode());
System.out.println("Request ID:      " + oe.getRequestId());
System.out.println("Host ID:           " + oe.getHostId());
} catch (ClientException ce) {
System.out.println("Caught an ClientException, which means the client encountered "
+ "a serious internal problem while trying to communicate with OSS, "
+ "such as not being able to access the network.");
System.out.println("Error Message: " + ce.getMessage());
} catch (Exception e) {
e.printStackTrace();
continue;
} finally {
client.shutdown();
}

if (fileNames == null)
fileNames = fileName;
else
fileNames += "," + fileName;
}
}
os.write((Constants.SUCCESS + "|" + fileNames).getBytes("UTF-8"));
os.close();
return;
}

public static String getTempPath(String filePath) {
String projectName = AppConfig.PROJECT_NAME;
String ret = AppConfig.getResourceHome();
String contextPath = AppConfig.getContextPath();
if (!contextPath.equals(projectName) && ret.contains(projectName)) {
ret = ret.substring(0, ret.indexOf(projectName) - 1);
}
String path = ret + AppConfig.RESOURCE_APP_ROOT + filePath;
// 文件上传目录
File sourceFile = new File(path);
if (!sourceFile.exists()) {
sourceFile.mkdirs();
}
return path;
}

/**
* 获取文件名
* UUID 拼接 8位日期
*
* 如需获得原图,可将图片名称截后六位即图片创建日期,然后到file文件夹下根据日期即可找到
* @return
*/
public static String getFileName(){
String uuid = UUID.randomUUID().toString().replace("-", "");
String time = Convert.toShortYMDWithNoSplit(new Date());
return uuid + time;
}
}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签:  图片 服务器
相关文章推荐