使用Http协议向服务器传递图片,那么就要首先了解Http协议这个报文里边的信息格式:
web端传递图片一般都是使用表单的形式来传递的,通过post的形式传递的,在这里要使用到两个jar包,分别是:commons-fileupload.jar和commons-io.jar这俩jar包。
下边来说一说Http协议上传文件头文件的格式:
其实我们这种前后台的交互是用的HTTP协议。而http协议默认是传的字符串。所以我们上传文件的话要加enctype = "multipart/form-data"这个参数来说明我们这传的是文件不是字符串了。而我们做web开发的时候,浏览器是自动解析HTTP协议的。里面传的哪些东西我们不用管。只要记住几个参数就行。而我们要上传的文件报文是保存在请求的头文件里面的。下面就是上传文件头文件的格式:
POST/logsys/home/uploadIspeedLog!doDefault.html HTTP/1.1
Accept: text/plain, */*
Accept-Language: zh-cn
Host: 192.168.24.56
Content-Type:multipart/form-data;boundary=-----------------------------7db372eb000e2
User-Agent: WinHttpClient
Content-Length: 3693
Connection: Keep-Alive
-------------------------------7db372eb000e2
Content-Disposition: form-data; name="file"; filename="kn.jpg"
Content-Type: image/jpeg
(此处省略jpeg文件二进制数据...)
-------------------------------7db372eb000e2--
这就是Http上传发送的文件格式。而我们要发送的时候必然要遵循这种格式来并且不能出一点差错包括每行后面的回车,下面一段文字是网上找的感觉写的比较精彩。(尊重原创:http://topmanopensource.iteye.com/blog/1605238)
红色字体部分就是协议的头。给服务器上传数据时,并非协议头每个字段都得说明,其中,content-type是必须的,它包括一个类似标志性质的名为boundary的标志,它可以是随便输入的字符串。对后面的具体内容也是必须的。它用来分辨一段内容的开始。Content-Length: 3693 ,这里的3693是要上传文件的总长度。绿色字体部分就是需要上传的数据,可以是文本,也可以是图片等。数据内容前面需要有Content-Disposition, Content-Type以及Content-Transfer-Encoding等说明字段。最后的紫色部分就是协议的结尾了。
注意这一行:
Content-Type: multipart/form-data; boundary=---------------------------7db372eb000e2
根据 rfc1867, multipart/form-data是必须的.
---------------------------7db372eb000e2 是分隔符,分隔多个文件、表单项。其中b372eb000e2 是即时生成的一个数字,用以确保整个分隔符不会在文件或表单项的内容中出现。Form每个部分用分隔符分割,分隔符之前必须加上"--"着两个字符(即--{boundary})才能被http协议认为是Form的分隔符,表示结束的话用在正确的分隔符后面添加"--"表示结束。
前面的 ---------------------------7d 是 IE 特有的标志,Mozila 为---------------------------71.
只要把这些Http协议的头部的格式梳理清楚,然后再把图片向服务器传递:直接上代码:
//客户端代码
public class HttpPost { /** * 通过拼接的方式构造请求内容,实现参数传输以及文件传输 * * @param acti * .nUrl * @param params * @param files * @return * @throws IOException */ public static String post(String actionUrl, Map<String, String> params, Map<String, File> files) throws IOException { String BOUNDARY = java.util.UUID.randomUUID().toString(); String PREFIX = "--", LINEND = "\r\n"; String MULTIPART_FROM_DATA = "multipart/form-data"; String CHARSET = "UTF-8"; URL uri = new URL(actionUrl); HttpURLConnection conn = (HttpURLConnection) uri.openConnection(); conn.setReadTimeout(5 * 1000); // 缓存的最长时间 conn.setDoInput(true);// 允许输入 conn.setDoOutput(true);// 允许输出 conn.setUseCaches(false); // 不允许使用缓存 conn.setRequestMethod("POST"); conn.setRequestProperty("connection", "keep-alive"); conn.setRequestProperty("Charsert", "UTF-8"); conn.setRequestProperty("Content-Type", MULTIPART_FROM_DATA + ";boundary=" + BOUNDARY); // 首先组拼文本类型的参数 StringBuilder sb = new StringBuilder(); for (Map.Entry<String, String> entry : params.entrySet()) { sb.append(PREFIX); sb.append(BOUNDARY); sb.append(LINEND); sb.append("Content-Disposition: form-data; name=\"" + entry.getKey() + "\"" + LINEND); sb.append("Content-Type: text/plain; charset=" + CHARSET + LINEND); sb.append("Content-Transfer-Encoding: 8bit" + LINEND); sb.append(LINEND); sb.append(entry.getValue()); sb.append(LINEND); } DataOutputStream outStream = new DataOutputStream(conn.getOutputStream()); outStream.write(sb.toString().getBytes()); // 发送文件数据 if (files != null) for (Map.Entry<String, File> file : files.entrySet()) { StringBuilder sb1 = new StringBuilder(); sb1.append(PREFIX); sb1.append(BOUNDARY); sb1.append(LINEND); sb1.append("Content-Disposition: form-data; name=\"file\"; filename=\"" + file.getKey() + "\"" + LINEND); sb1.append("Content-Type: application/octet-stream; charset=" + CHARSET + LINEND); sb1.append(LINEND); outStream.write(sb1.toString().getBytes()); InputStream is = new FileInputStream(file.getValue()); byte[] buffer = new byte[1024]; int len = 0; while ((len = is.read(buffer)) != -1) { outStream.write(buffer, 0, len); } is.close(); outStream.write(LINEND.getBytes()); } // 请求结束标志 byte[] end_data = (PREFIX + BOUNDARY + PREFIX + LINEND).getBytes(); outStream.write(end_data); outStream.flush(); // 得到响应码 int res = conn.getResponseCode(); InputStream in = conn.getInputStream(); if (res == 200) { int ch; StringBuilder sb2 = new StringBuilder(); while ((ch = in.read()) != -1) { sb2.append((char) ch); } } outStream.close(); conn.disconnect(); return in.toString(); } }
下边是服务器代码:
public class UploadServlet extends HttpServlet { private static final long serialVersionUID = 1L; /** * Default constructor. */ public UploadServlet() { // TODO Auto-generated constructor stub } /** * @see HttpServlet#doGet(HttpServletRequest request, HttpServletResponse * response) */ protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { // TODO Auto-generated method stub } /** * @see HttpServlet#doPost(HttpServletRequest request, HttpServletResponse * response) */ public void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { RequestContext req = new ServletRequestContext(request); if (FileUpload.isMultipartContent(req)) { DiskFileItemFactory factory = new DiskFileItemFactory(); ServletFileUpload fileUpload = new ServletFileUpload(factory); fileUpload.setFileSizeMax(1024 * 1024 * 1024); List items = new ArrayList(); try { items = fileUpload.parseRequest(request); } catch (Exception e) { } Iterator it = items.iterator(); while (it.hasNext()) { FileItem fileItem = (FileItem) it.next(); if (fileItem.isFormField()) { System.out.println(fileItem.getFieldName() + " " + fileItem.getName() + " " + new String(fileItem.getString().getBytes( "ISO-8859-1"), "GBK")); } else { System.out.println(fileItem.getFieldName() + " " + fileItem.getName() + " " + fileItem.isInMemory() + " " + fileItem.getContentType() + " " + fileItem.getSize()); if (fileItem.getName() != null && fileItem.getSize() != 0) { File fullFile = new File(fileItem.getName()); File newFile = new File("F:\\upload\\" + fullFile.getName()); try { fileItem.write(newFile); } catch (Exception E) { } } else { System.out.println("no file choosen or empty file"); } } } } } }