zoukankan      html  css  js  c++  java
  • 利用HttpClient进行带参数的http文件上传

    注意:要引用commons-httpclient-3.1.jar

    commons-codec.jar

    commons-logging.jar这三个包

    客户端例子代码

    import java.io.File;
    
    import org.apache.commons.httpclient.HttpClient;
    import org.apache.commons.httpclient.HttpStatus;
    import org.apache.commons.httpclient.methods.PostMethod;
    import org.apache.commons.httpclient.methods.multipart.FilePart;
    import org.apache.commons.httpclient.methods.multipart.StringPart;
    import org.apache.commons.httpclient.methods.multipart.MultipartRequestEntity;
    import org.apache.commons.httpclient.methods.multipart.Part;
    
    public class Hclient
    {
    public static void main(String args[])
    {
       String targetURL = null;// TODO 指定URL
       File targetFile = null;// TODO 指定上传文件
      
       targetFile = new File("1.mp3");
       targetURL = "http://localhost:8080/test/uploadFile"; //servleturl
       PostMethod filePost = new PostMethod(targetURL);
      
       try
       {
    
     
       Part[] parts = { 
        new FilePart(targetFile.getName(), targetFile),
        new StringPart("parm1","parm1Value")
         };
        filePost.setRequestEntity(new MultipartRequestEntity(parts,filePost.getParams()));
        HttpClient client = new HttpClient();
        client.getHttpConnectionManager().getParams().setConnectionTimeout(5000);
        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();
       }
    }
    } 
    

      服务器端代码:

    @RequestMapping(“/test/uploadFile")
    public ModelAndView saveUpload(
    @RequestParam("uploadFile") MultipartFile file,
     HttpServletRequest request)
    {
            String dir =request.getSession().getServetContext().getRealPath("uploadDir");
            File newPath = new File(dir +"saveFileName.zip");
            file.transferTo(newPath);      
    }    
  • 相关阅读:
    XCode5中新建工程后强制使用了ARC,如何去掉?
    面向对象程序的设计原则--Head First 设计模式笔记
    ios控件自定义指引
    iOS UITableViewDelegate && UITableViewDataSource 执行顺序
    awakeFromNib方法和viewDidLoad方法区别
    ios 视图的旋转及应用
    线段树模板 (刘汝佳)
    poj 3468
    hdu 2829(四边形优化 && 枚举最后一个放炸弹的地方)
    poj 3517(约瑟夫环问题)
  • 原文地址:https://www.cnblogs.com/zitjubiz/p/java_httpclient_upload_file.html
Copyright © 2011-2022 走看看