您的位置:首页 > 移动开发 > Android开发

Android、IOS 图片上传接口(Java实现Servlet)。

2015-09-26 11:18 731 查看

1、java Servlet 实现图片上传代码。(返回结果格式为json格式)

package com.ninepoint.babystar.server.action;

import java.io.File;
import java.io.IOException;
import java.io.PrintWriter;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import net.sf.json.JSONObject;

import org.apache.commons.fileupload.FileItem;
import org.apache.commons.fileupload.disk.DiskFileItemFactory;
import org.apache.commons.fileupload.servlet.ServletFileUpload;
import org.apache.log4j.Logger;

import com.ninepoint.babystar.server.bean.ResultBaseBean;
/**
*
* @Description 图片上传接口(Servlet实现)支持参数和多张图片的上传
* @author nier_ni
* @date 2015-9-26 上午11:05:52
* @version
*/
public class UploadFileServlet extends HttpServlet {
/** @Fields serialVersionUID: */

private static final long serialVersionUID = -4903483985922185852L;
private final Logger logger = Logger.getLogger(UploadFileServlet.class);

public void doGet(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
String realPath = this.getServletContext().getRealPath("images");  //图片保存路径
ResultBaseBean result = new ResultBaseBean();
result.setResult(0);
boolean isMultipart = ServletFileUpload.isMultipartContent(request);
if(isMultipart){
/**
* 1、上传是否有数据;
* 2、图片存放路径;
* 3、图片是否保存成功。 result 1、上传成功,0、上传失败。
*/
String msg = null;
HashMap<String,String> params = uploadImg(realPath,request);
responseOutWithJson(response,result);
}
}
public void doPost(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
this.doGet(request,response);
}
/**
*
* @Description 上传图片
* @param realPath
* @param request
*/
public HashMap<String,String> uploadImg(String realPath, HttpServletRequest request){
HashMap<String,String> hashMap = new HashMap<String, String>();
int i = 0;
String fileName = null;
File dir = new File(realPath);
DiskFileItemFactory factory = new DiskFileItemFactory();
ServletFileUpload upload = new ServletFileUpload(factory);
upload.setSizeMax(1024*1024*5*9);
upload.setHeaderEncoding("utf-8");
try {
List<FileItem> items = upload.parseRequest(request);
for(FileItem item : items){
if(item.isFormField()){ //username="username"
String name = item.getFieldName();
String value = item.getString("utf-8");
//System.out.println(name + " = " + value);
hashMap.put(name, value);
} else { //文件
String name = item.getName();
fileName = System.currentTimeMi
c295
llis() + name.substring(name.lastIndexOf("."));
// item.write(new File(dir, System.currentTimeMillis() + name.substring(name.lastIndexOf("."))));
item.write(new File(dir, fileName));
hashMap.put("imgs"+i,realPath.substring(realPath.lastIndexOf("\\")).substring(1) +"/"+ fileName);
}
}
hashMap.put("num",i+"");
} catch (Exception e) {
e.printStackTrace();
logger.error("图片上传失败。",e);
}
return hashMap;
}
/**
* 以JSON格式输出
* @param response
*/
protected void responseOutWithJson(HttpServletResponse response,
Object responseObject) {
//将实体对象转换为JSON Object转换
JSONObject responseJSONObject = JSONObject.fromObject(responseObject);
response.setCharacterEncoding("UTF-8");
response.setContentType("application/json; charset=utf-8");
PrintWriter out = null;
try {
out = response.getWriter();
out.append(responseJSONObject.toString());
logger.debug("返回是\n");
logger.debug(responseJSONObject.toString());
} catch (IOException e) {
e.printStackTrace();
} finally {
if (out != null) {
out.close();
}
}
}
}
结果基类
package com.ninepoint.babystar.server.bean;

import java.io.Serializable;

import net.sf.json.JSONObject;

/**
* 请求返回结果基类。
* 返回结果的公共数据可以放在此类
* @author nier_ni
*
*/
public class ResultBaseBean implements Serializable{

private static final long serialVersionUID = 7755697531438413626L;

/**
* 请求结果 1代表成功  0代表失败
* 默认为成功
*/
protected int result = 1;
/**
* 错误编码
* 只有当 result为0时才有 errorCode 和 errorMsg
*/
protected String errorCode = "";
/**错误信息*/
protected String errorMsg = "";

protected Object data = null;

public Object getData() {
return data;
}

public void setData(Object data) {
this.data = data;
}

public int getResult() {
return result;
}

public void setResult(int result) {
this.result = result;
}

public String getErrorCode() {
return errorCode;
}

public void setErrorCode(String errorCode) {
this.errorCode = errorCode;
}

public String getErrorMsg() {
return errorMsg;
}

public void setErrorMsg(String errorMsg) {
this.errorMsg = errorMsg;
}

public JSONObject toJsonObject(){
JSONObject jo = new JSONObject();
jo.put("result", result);
jo.put("errorCode", errorCode);
jo.put("errorMsg", errorMsg);
jo.put("data", data.toString());
return jo;
}

@Override
public String toString() {
return this.toJsonObject().toString();
}
}
web.xml配置
<servlet>
<span style="white-space:pre">	</span><servlet-name>uploadFileServlet</servlet-name>
<span style="white-space:pre">	</span><servlet-class>com.ninepoint.babystar.server.action.UploadFileServlet</servlet-class>
</servlet>
<servlet-mapping>
<servlet-name>uploadFileServlet</servlet-name>
<url-pattern>/uploadFileServlet</url-pattern>
</servlet-mapping>

2、测试上传图片(模拟发送上传图片请求)。

package com.ninepoint.babystar.test.action;

import java.io.BufferedReader;
import java.io.DataOutputStream;
import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.OutputStream;
import java.net.HttpURLConnection;
import java.net.MalformedURLException;
import java.net.URL;
import java.util.UUID;
/**
*
* @Description 图片上传模拟HTTP请求
* @author nier_ni
* @date 2015-9-26 上午11:17:24
* @version
*/
public class HttpAssist {
private static final String TAG = "uploadFile";
private static final int TIME_OUT = 10 * 10000000; // 超时时间
private static final String CHARSET = "utf-8"; // 设置编码
public static final String SUCCESS = "1";
public static final String FAILURE = "0";

public static String uploadFile(File file) {
String BOUNDARY = UUID.randomUUID().toString(); // 边界标识 随机生成
String PREFIX = "--", LINE_END = "\r\n";
String CONTENT_TYPE = "multipart/form-data"; // 内容类型
String RequestURL = "http://192.168.1.161:8080/uploadFileServlet";
try {
URL url = new URL(RequestURL);
HttpURLConnection conn = (HttpURLConnection) url.openConnection();
conn.setReadTimeout(TIME_OUT);
conn.setConnectTimeout(TIME_OUT);
conn.setDoInput(true); // 允许输入流
conn.setDoOutput(true); // 允许输出流
conn.setUseCaches(false); // 不允许使用缓存
conn.setRequestMethod("POST"); // 请求方式
conn.setRequestProperty("Charset", CHARSET); // 设置编码
conn.setRequestProperty("connection", "keep-alive");
conn.setRequestProperty("Content-Type", CONTENT_TYPE + ";boundary="
+ BOUNDARY);
if (file != null) {
/**
* 当文件不为空,把文件包装并且上传
*/
OutputStream outputSteam = conn.getOutputStream();

DataOutputStream dos = new DataOutputStream(outputSteam);
StringBuffer sb = new StringBuffer();
sb.append(PREFIX);
sb.append(BOUNDARY);
sb.append(LINE_END);
/**
* 这里重点注意: name里面的值为服务器端需要key 只有这个key 才可以得到对应的文件
* filename是文件的名字,包含后缀名的 比如:abc.png
*/

sb.append("Content-Disposition: form-data; name=\"img\"; filename=\""
+ file.getName() + "\"" + LINE_END);
sb.append("Content-Type: application/octet-stream; charset="
+ CHARSET + LINE_END);
sb.append(LINE_END);
dos.write(sb.toString().getBytes());
InputStream is = new FileInputStream(file);
byte[] bytes = new byte[1024];
int len = 0;
while ((len = is.read(bytes)) != -1) {
dos.write(bytes, 0, len);
}
is.close();
dos.write(LINE_END.getBytes());
byte[] end_data = (PREFIX + BOUNDARY + PREFIX + LINE_END)
.getBytes();
dos.write(end_data);
dos.flush();
/**
* 获取响应码 200=成功 当响应成功,获取响应的流
*/
int res = conn.getResponseCode();
if (res == 200) {
return SUCCESS;
}
}
} catch (MalformedURLException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
return FAILURE;
}
}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息