客户端代码:
public void run() {
String boundry = UUID.randomUUID().toString(); // 边界标识
String prefix = "--", end = "\r\n";
File file = new File(imagePath);
try {
URL Url = new URL(url);
HttpURLConnection conn = (HttpURLConnection) Url.openConnection();
conn.setReadTimeout(5000);
conn.setDoInput(true);
conn.setDoOutput(true);
conn.setRequestMethod("POST");
conn.setRequestProperty("Content-type", "multipart/form-data;boundary=" + boundry);
if (file != null) {
DataOutputStream out = new DataOutputStream(conn.getOutputStream());
out.writeBytes(prefix + boundry + end);
out.writeBytes("Content-Disposition: form-data;" + "name=\"file\"; filename=\"" + file.getName()
+ "\"" + end);
out.writeBytes(end);
FileInputStream fis = new FileInputStream(file);
byte[] b = new byte[1024];
int len = 0;
while ((len = fis.read(b)) != -1) {
out.write(b, 0, len);
}
out.writeBytes(end);
out.writeBytes(prefix + boundry + prefix + end);
out.flush();
BufferedReader reader = new BufferedReader(new InputStreamReader(conn.getInputStream()));
StringBuffer sb = new StringBuffer();
String str = "";
while ((str = reader.readLine()) != null) {
sb.append(str);
}
if (out != null) {
out.close();
}
if (reader != null) {
reader.close();
}
}
} catch (MalformedURLException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
服务器代码:
protected void doPost(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
request.setCharacterEncoding("utf-8");
DiskFileItemFactory factory = new DiskFileItemFactory();
String path = request.getSession().getServletContext().getRealPath("/WEB-INF/upload");
factory.setRepository(new File(path));
factory.setSizeThreshold(1024 * 1024);
ServletFileUpload upload = new ServletFileUpload(factory);
try {
List<FileItem> list = (List<FileItem>) upload.parseRequest(request);
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("\\");
String filename = value.substring(start + 1);
request.setAttribute(name, filename);
try {
item.write(new File(path, filename));
} catch (Exception e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
}
} catch (FileUploadException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
}