随笔 - 435  文章 - 0  评论 - 111  阅读 - 62万 

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

commons-codec.jar

commons-logging.jar这三个包

客户端例子代码

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
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);      
}    
复制代码

 

posted on   Gu  阅读(7283)  评论(0编辑  收藏  举报
编辑推荐:
· Linux系列:如何用heaptrack跟踪.NET程序的非托管内存泄露
· 开发者必知的日志记录最佳实践
· SQL Server 2025 AI相关能力初探
· Linux系列:如何用 C#调用 C方法造成内存泄露
· AI与.NET技术实操系列(二):开始使用ML.NET
阅读排行:
· 无需6万激活码!GitHub神秘组织3小时极速复刻Manus,手把手教你使用OpenManus搭建本
· C#/.NET/.NET Core优秀项目和框架2025年2月简报
· 什么是nginx的强缓存和协商缓存
· 一文读懂知识蒸馏
· Manus爆火,是硬核还是营销?
点击右上角即可分享
微信分享提示