HttpClient 3.1 文件上传

HttpClient 3.1 文件上传

客户端:

需要commons-codec,commons-httpclient-3.1,commons-logging-1.1.1

 String targetURL = null;// TODO 指定URL File targetFile = null;// TODO 指定上传文件 targetFile = new File("C:\\Users\\Administrator\\Desktop\\1.mp3"); targetURL = "http://localhost:8080/HttpClientDemo/test"; //servleturl PostMethod filePost = new PostMethod(targetURL); try { //通过以下方法可以模拟页面参数提交 filePost.setParameter("name", "中文"); filePost.setParameter("pass", "1234"); Part[] parts = { new FilePart(targetFile.getName(), targetFile) }; filePost.setRequestEntity(new MultipartRequestEntity(parts,filePost.getParams())); HttpClient client = new HttpClient(); client.getHttpConnectionManager().getParams().setConnectionTimeout(10000); int status = client.executeMethod(filePost); if (status == HttpStatus.SC_OK) { System.out.println("上传成功"); // 上传成功 } else { System.out.println("上传失败"); // 上传失败 } } catch (Exception ex) { ex.printStackTrace(); } finally { filePost.releaseConnection(); }

服务器端:

需要commons-fileupload-1.2.1.jar commons-io.jar

public class HttpClientTest extends HttpServlet { private String uploadPath = "D:\\temp"; // 上传文件的目录 private String tempPath = "d:\\temp\\buffer\\"; // 临时文件目录 File tempPathFile; public void init() throws ServletException { File uploadFile = new File(uploadPath); if (!uploadFile.exists()) { uploadFile.mkdirs(); } File tempPathFile = new File(tempPath); if (!tempPathFile.exists()) { tempPathFile.mkdirs(); } } // @Override // protected void service(HttpServletRequest request, HttpServletResponse response) // throws ServletException, IOException { // String name=request.getParameter("name"); System.out.println("name: "+name); request.getRequestDispatcher("index.jsp").forward(request, response); // // // // } public void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { try { System.out.println("dopost"); // Create a factory for disk-based file items DiskFileItemFactory factory = new DiskFileItemFactory(); // Set factory constraints factory.setSizeThreshold(4096); // 设置缓冲区大小,这里是4kb factory.setRepository(tempPathFile);// 设置缓冲区目录 // Create a new file upload handler ServletFileUpload upload = new ServletFileUpload(factory); // Set overall request size constraint upload.setSizeMax(10*1024*1024); // 设置最大文件尺寸,这里是10MB List<FileItem> items = upload.parseRequest(request);// 得到所有的文件 Iterator<FileItem> i = items.iterator(); while (i.hasNext()) { FileItem fi = (FileItem) i.next(); String fileName = fi.getName(); System.out.println(fileName); if (fileName != null) { File fullFile = new File(fi.getName()); File savedFile = new File(uploadPath, fullFile.getName()); fi.write(savedFile); } } System.out.print("upload succeed"); } catch (Exception e) { System.out.println(e.getMessage()); // 可以跳转出错页面 e.printStackTrace(); } } }

转载于:https://my.oschina.net/joeytai/blog/521140

版权声明:本文内容由互联网用户自发贡献,该文观点仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请联系我们举报,一经查实,本站将立刻删除。

发布者:全栈程序员-站长,转载请注明出处:https://javaforall.net/109282.html原文链接:https://javaforall.net

(0)
全栈程序员-站长的头像全栈程序员-站长


相关推荐

  • 数据库query用法_query方法

    数据库query用法_query方法1、以前写代码,总免不了要编写登录部分。在获取user的时候,只可能返回一个user实例,或者为null。以前使用以下方法实现:publicUserget(Stringname,Stringpassword){Sessionsession=HibernateUtil.getSessionFactory().openSession();String…

    2022年9月30日
    0
  • 阵列信号DOA估计系列(三).MVDR/Capon波束形成(附代码)

    阵列信号DOA估计系列(三).MVDR/Capon波束形成(附代码)本文主要介绍Capn波束形成算法,又名最小方差无失真相应(MinimumVarianceDistortionlessResponse,MVDR),并将其方法应用于DOA估计。

    2022年6月26日
    31
  • 学习日志之synthesis and optimization(4)——banding and sharing

    学习日志之synthesis and optimization(4)——banding and sharing一个设计好的电路经过调度算法之后可以避免在时间上的一些限制,但是前面说的算法并没有涉及到硬件资源方面的constrains。在这里主要是开始进行资源的分配,这个过程在空间域上进行的资源与操作的绑定和分享。当然实际情况下并不仅仅需要考虑单一的时间域限制或是仅考虑空间域限制。而是需要两者同时考虑。要充分描述一个电路结构就需要以下一些元素:1.资源(resorces):用于在电路中实现各种算法…

    2022年10月9日
    0
  • Android游戏引擎_开源可视化规则引擎

    Android游戏引擎_开源可视化规则引擎1、AngleAngle是一款专为Android平台设计的,敏捷且适合快速开发的2D游戏引擎,基于OpenGLES技术开发。该引擎全部用Java代码编写,并且可以根据自己的需要替换里面的实现,缺陷在于文档不足,而且下载的代码中仅仅包含有少量的示例教程。最低运行环境要求不详。项目地址:http://code.google.com/p/angle/2、Rokonrokon是一

    2022年9月19日
    0
  • openCV中cvSnakeImage()函数代码分析

    openCV中cvSnakeImage()函数代码分析/*M///////////////////////////////////////////////////////////////////////////////////////////IMPOR

    2022年7月3日
    19
  • 大话数据结构PDF/word

    大话数据结构PDF/word《大话数据结构》PDF版本链接:https://pan.baidu.com/s/1nfaEZBBEi-3-mTX7A4qfbA提取码:30kyword版本链接:https://pan.baidu.com/s/18hpIqQYy4wiVUAoBabqZ-A提取码:e4ja

    2022年6月24日
    39

发表回复

您的邮箱地址不会被公开。 必填项已用 * 标注

关注全栈程序员社区公众号