标签:
1.服务端
1.1 相关jar包
<dependency> <groupId>commons-fileupload</groupId> <artifactId>commons-fileupload</artifactId> <version>1.3.1</version> </dependency>
1.2代码
public class Upload extends HttpServlet { private static final long serialVersionUID = 1L; @Override protected void service(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException { try { String fileDir="e:/fileUpload/"; DiskFileItemFactory dfif=new DiskFileItemFactory(4, new File("e:/tempPath")); ServletFileUpload sfu=new ServletFileUpload(dfif); List<FileItem> files= sfu.parseRequest(req); if(files!=null){ for (FileItem fileItem : files) { String fileName= fileItem.getName(); fileItem.write(new File(fileDir+fileName)); } } } catch (Exception e) { e.printStackTrace(); } } }
2.客户端
HttpPost httpPost = new HttpPost(actionUrl); MultipartEntity reqEntity = new MultipartEntity(HttpMultipartMode.BROWSER_COMPATIBLE,null,Charset.forName(HTTP.UTF_8)); FileBody file1 = new FileBody(myPhoto,"image", "UTF-8"); reqEntity.addPart("file1", file1); httpPost.setEntity(reqEntity);
HttpClient httpclient =new DefaultHttpClient(); httpclient.getParams().setParameter(CoreProtocolPNames.PROTOCOL_VERSION, HttpVersion.HTTP_1_1); // httpclient.getParams().setParameter(CoreProtocolPNames.HTTP_CONTENT_CHARSET, Charset.forName("UTF-8")); httpResponse = httpclient.execute(httpPost);
标签:
原文地址:http://www.cnblogs.com/mmdsnb/p/4849745.html