- 在实际应用中 一般是有多个服务器的
- 先配置一个图片服务器
- 并创建存储文件夹uploads
- 部署到Tomcat
- 先开启图片服务器fileupload
- 然后准备在主服务器接受客户端的request请求,并创建客户端对象和图片服务器fileupload连接完成跨服务器文件上传(通过字节)
package com.czh.controller;
import com.sun.jersey.api.client.Client;
import com.sun.jersey.api.client.WebResource;
import org.apache.commons.fileupload.FileItem;
import org.apache.commons.fileupload.FileUploadException;
import org.apache.commons.fileupload.disk.DiskFileItemFactory;
import org.apache.commons.fileupload.servlet.ServletFileUpload;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.multipart.MultipartFile;
import javax.servlet.http.HttpServletRequest;
import java.io.File;
import java.io.IOException;
import java.util.List;
import java.util.UUID;
/**
* @author zhCoding
* @Description:
* @create 17:38
*/
@Controller
@RequestMapping("/user")
public class UserController {
@RequestMapping("/fileUpLoad3")
public String fileUpLoad3(@RequestParam("uploadddd") MultipartFile upload) throws IOException {
System.out.println("SpringMVC跨服务器文件上传3....");
//定义上传文件服务器路径
String realPath = "http://localhost:9090/FileuploadServer_war_exploded/uploads/";
String filename = upload.getOriginalFilename();
String uuid = UUID.randomUUID().toString().replace("-", "");
filename = uuid+"_"+filename;
//创建客户端对象
Client client = Client.create();
//和图片服务器fileupload连接
WebResource webResource = client.resource(realPath + filename);
//完成跨服务器文件上传(通过字节)
webResource.put(upload.getBytes());
return "success";
}
}
注意:上传可能会遇到Tomcat服务器错误
即:message Request processing failed; nested exception is com.sun.jersey.api.client.UniformInterfaceException: PUT http://localhost:9090/FileuploadServer_war_exploded/uploads/ef4510773995444480242047cceacf1b_DSC_0150.jpg returned a response status of 403 Forbidden
这是由于本机的Tomcat没有开启写权限
此时在图中文件里添加写权限即可: