第一步,打开两个tomcat不同版本,一个tomcat用来实现文件上传(暂且称为A服务器)这里我用的maven工程,一个tomcat用来接收文件(暂且称为b服务器)这里可以用一个普通的web工程;
首先打开b服务器的web.xml文件添加
<init-param>
<param-name>readonly</param-name>
<param-value>false</param-value>
</init-param>
表示当前服务器可以写入
第二步:在A服务器下导入下包
//文件上传所需要依赖包
<dependency>
<groupId>commons-io</groupId>
<artifactId>commons-io</artifactId>
<version>2.6</version>
</dependency>
<!-- https://mvnrepository.com/artifact/commons-fileupload/commons-fileupload -->
<dependency>
<groupId>commons-fileupload</groupId>
<artifactId>commons-fileupload</artifactId>
<version>1.4</version>
</dependency>
//实现跨服务器文件上传所需要的依赖包
- https://mvnrepository.com/artifact/com.sun.jersey/jersey-core -->
<dependency>
<groupId>com.sun.jersey</groupId>
<artifactId>jersey-core</artifactId>
<version>1.19.4</version>
</dependency>
<!-- https://mvnrepository.com/artifact/com.sun.jersey/jersey-client -->
<dependency>
<groupId>com.sun.jersey</groupId>
<artifactId>jersey-client</artifactId>
<version>1.19.4</version>
</dependency>
第三步:在A服务器端编写前端页面
<form action="/he" method="post" enctype="multipart/form-data">
<input type="file" name="filename" >
<input type="submit" value="提交">
</form>
第三步编写controller端业务
@RequestMapping("/he")
public String show1( MultipartFile filename) throws NTLMException, IOException {
//这个是B服务器的地址
final String ADDRESS="http://localhost:9090/";
//获取上传文件的名字
String originalFilename = filename.getOriginalFilename();
//使用uuid将名字修改,主要是为了安全问题
String filenewname=UUID.randomUUID()+"-"+originalFilename;
//创建客户端
Client client=Client.create();
WebResource resource = client.resource(ADDRESS+filenewname);
//将资源发送过去
String put = resource.put(String.class, filename.getInputStream());
return "hello";
}
注意,方法中的参数名(MultipartFile filename)必须和页面中的<input type="file" name="filename" >
中的name对应
第四步:分别启动两个服务器,(这里B服务器需要修改端口号以及JMX port,两个服务器要不一样)经行访问
这里有个问题。就是上传的文件名字最好不要是中文,否则会出错,如果要使用中文文件名字需要经行编码
URLEncoder.encode(filenewname,"utf-8");