前提
1. form表单请求方式必须是post
2. 添加form表单的参数:enctype 多部件表单类型 enctype="multipart/form-data"
3. 引入依赖:commons-upload, commons-io
1、文件上传到当前服务器
a、引入依赖
<!-- 引入fileUpload会自动依赖commons-io -->
<dependency>
<groupId>commons-fileupload</groupId>
<artifactId>commons-fileupload</artifactId>
<version>1.3.1</version>
</dependency>
b、spring-mvc.xml 配置文件
<!-- 配置文件上传解析器 -->
<!-- id的值是固定的-->
<bean id="multipartResolver"
class="org.springframework.web.multipart.commons.CommonsMultipartResolver">
<!-- 设置上传文件的最大尺寸为5MB -->
<property name="maxUploadSize">
<value>5242880</value>
</property>
</bean>
c、页面配置
<form action="${pageContext.request.contextPath}/upload" method="post" enctype="multipart/form-data">
<input type="file" name="uploadFile">
<input type="text" name="username">
<input type="submit" value="上传">
</form>
d、controller代码
@Controller()
public class UploadController {
/**
* 本地上传
MultipartFile接口方法:
- String getOriginalFilename()获取上传文件名
- byte[] getBytes()文件转成字节数组
- void transferTo(File file)转换方法,将上传文件转换到File对象
*/
@RequestMapping("/upload")
public String upload(MultipartFile uploadFile, HttpServletRequest request){
//32位的随机内容的字符串
String uuid = UUID.randomUUID().toString().replace("-","");
//文件名称
String filename = uploadFile.getOriginalFilename();
System.out.println("filename = " + filename);
//文件上传
String realPath = request.getSession().getServletContext().getRealPath(request.getContextPath() + "/upload");
File path = new File(realPath, uuid+filename);
try {
uploadFile.transferTo(path);
} catch (IOException e) {
e.printStackTrace();
}
return "success";
}
}
2、跨服上传
a、引入依赖
<!--引入jersey服务器的包-->
<dependency>
<groupId>com.sun.jersey</groupId>
<artifactId>jersey-core</artifactId>
<version>1.18.1</version>
</dependency>
<dependency>
<groupId>com.sun.jersey</groupId>
<artifactId>jersey-client</artifactId>
<version>1.18.1</version>
</dependency>
b、修改tomcat配置
1. tomcat默认不能跨服上传的
2. tomcat/conf/web.xml
<!--需要添加的-->
<init-param>
<param-name>readonly</param-name>
<param-value>false</param-value>
</init-param>
c、配置图片服务器
1. 创建一个web项目
2. 配置一个tomcat,与原来tomcat端口号不一致
3. 在webapp目录下创建一个upload目录,空的文件夹不会编译,需要在upload目录添加(任意)一个文件
d、修改controller代码
/**
* 跨服上传
MultipartFile接口方法:
- String getOriginalFilename()获取上传文件名
- byte[] getBytes()文件转成字节数组
*/
@RequestMapping("/upload")
public String upload(MultipartFile uploadFile, HttpServletRequest request){
//32位的随机内容的字符串
String uuid = UUID.randomUUID().toString().replace("-","");
//文件名称
String filename = uploadFile.getOriginalFilename();
System.out.println("filename = " + filename);
//跨服务器上传
String serverUrl = "http://localhost:8081/upload";
//向服务器上传的客户端对象
Client client = Client.create();
WebResource resource = client.resource(serverUrl + "/" + uuid + filename);
//执行上传文件到 指定的服务器
//转出字节数组开始上传
try {
resource.put(String.class, uploadFile.getBytes());
} catch (IOException e) {
e.printStackTrace();
}
return "success";
}