Android HttpURLConnection上传图片至Servlet端指定目录
客户端(核心代码):
/** * 文件上传 * * @param urlStr 接口路径 * @param filePath 本地图片路径 * @return */public static String formUpload(String urlStr, String filePath) { String rsp = ""; HttpURLConnection conn = null; String 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()); File file = new File(filePath); String filename = file.getName(); String contentType = ""; if (filename.endsWith(".png")) { contentType = "image/png"; } if (filename.endsWith(".jpg")) { contentType = "image/jpg"; } if (filename.endsWith(".gif")) { contentType = "image/gif"; } if (filename.endsWith(".bmp")) { contentType = "image/bmp"; } 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=\"" + filePath + "\"; 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 buffer = new StringBuffer(); BufferedReader reader = new BufferedReader(new InputStreamReader(conn.getInputStream(), "utf-8")); String line = null; while ((line = reader.readLine()) != null) { buffer.append(line).append("\n"); } rsp = buffer.toString(); reader.close(); reader = null; } catch (Exception e) { e.printStackTrace(); } finally { if (conn != null) { conn.disconnect(); conn = null; } } return rsp;}
服务端(核心代码):
public class upload extends HttpServlet {
public upload() {
super();
}
public void destroy() {
super.destroy();
}
/**
* The doGet method of the servlet.
* This method is called when a form has its tag value method equals to get.
* @param request the request send by the client to the server
* @param response the response send by the server to the client
* @throws ServletException if an error occurred
* @throws IOException if an error occurred
*/
public void doGet(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
response.setContentType("text/html");
PrintWriter out = response.getWriter();
out.println(
"");
out.println("");
out.println("
out.println(" ");
out.print(" This is ");
out.print(this.getClass());
out.println(", using the GET method");
out.println(" ");
out.println("");
out.flush();
out.close();
}
/**
* The doPost method of the servlet.
* This method is called when a form has its tag value method equals to
* post.
* @param request the request send by the client to the server
* @param response the response send by the server to the client
* @throws ServletException if an error occurred
* @throws IOException if an error occurred
*/
@SuppressWarnings("deprecation")
public void doPost(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
request.setCharacterEncoding("utf-8"); // 设置编码
// 获得磁盘文件条目工厂
DiskFileItemFactory factory = new DiskFileItemFactory();
// 设定文件需要上传到的路径
File file = new File("E://WebSite");
if (!file.exists()) {
file.mkdirs();
}
factory.setRepository(file);
// 设置 缓存的大小
factory.setSizeThreshold(1024 * 1024);
// 文件上传处理
ServletFileUpload upload = new ServletFileUpload(factory);
try {
// 可以上传多个文件
List
for (FileItem item : list) {
// 获取属性名字
String name = item.getFieldName();
// 如果获取的 表单信息是普通的 文本 信息
if (item.isFormField()) {
// 获取用户具体输入的字符串,因为表单提交过来的是 字符串类型的
String value = item.getString();
request.setAttribute(name, value);
} else {
// 获取路径名
String value = item.getName();
// 索引到最后一个反斜杠
int start = value.lastIndexOf("\\");
// 截取 上传文件的 字符串名字,加1是 去掉反斜杠,
String filename = value.substring(start + 1);
request.setAttribute(name, filename);
// 写到磁盘上
item.write(new File("E://WebSite", filename));// 第三方提供的
System.out.println("上传成功:" + filename);
response.getWriter().print(filename);// 将路径返回给客户端
}
}
} catch (Exception e) {
System.out.println("上传失败");
e.printStackTrace();
}
}
/**
* Initialization of the servlet.
* @throws ServletException if an error occurs
*/
public void init() throws ServletException {
// Put your code here
}
}
注对于commons-fileupload-1.4.jar和commons-io-1.4.jar而言,不仅仅需要在servlet工程中住进来,还要在本地的Tomcat/lib目录下面进行追加。
更多相关文章
- Android 获取屏幕截图 和保存到本地的sd卡路径下
- Windows下,Android Studio项目路径中包含中文字符无法编译的问题
- android--------根据文件路径加载指定文件
- Android studio 修改git路径
- Android 7.0调用相机拍照并获取图片路径
- android加载文件的方式,路径的写法
- android的路径问题
- Android Studio 中如何更改SDK路径
- Android EditText插入字符串到光标所在位置和删除