本地上传
第一步:需要导入两个jar
<dependency>
<groupId>commons-fileupload</groupId>
<artifactId>commons-fileupload</artifactId>
<version>1.3.1</version>
</dependency>
<dependency>
<groupId>commons-io</groupId>
<artifactId>commons-io</artifactId>
<version>2.4</version>
</dependency>
第二步:页面编写一个表单
<form action="${pageContext.request.contextPath}/upload" method="post" enctype="multipart/form-data">
选择图片:<input type="file" name="upload"><br>
<input type="submit" value="上传">
</form>
第三步:配置视图解析器
<!-- 配置文件上传解析器 -->
<bean id="multipartResolver" class="org.springframework.web.multipart.commons.CommonsMultipartResolver">
<!-- 设置上传文件的最大尺寸为 5MB -->
<property name="maxUploadSize">
<value>5242880</value>
</property>
</bean>
第四步:编写控制器
/***
* @Description 图片上传,本地上传
* @Param: [request, upload]
* @return: java.lang.String
*/
@RequestMapping(path = "/upload", method = RequestMethod.POST)
public String upload(HttpServletRequest request, MultipartFile upload) throws Exception {
if (upload != null) {
//获取上传的路径
String path = request.getSession().getServletContext().getRealPath("/uploads/");
File file = new File(path);
//如果目录为空创建目录
if (!file.exists()) {
file.mkdirs();
}
//获取上传文件的全名
String oldFileName = upload.getOriginalFilename();
//截取后缀名并统一转为小写后缀名
String suffixNmae = oldFileName.substring(oldFileName.lastIndexOf(".") + 1).toLowerCase();
//随机生成一串字符作为文件名称
String uuid = UUID.randomUUID().toString().replace("-", "");
//构建新的文件名称,防止文件名重复
String newFileName = uuid + "." + suffixNmae;
//上传文件
upload.transferTo(new File(file, newFileName));
}
return "success";
}
服务器上传
第一步:需要导入两个jar
<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>
第二步:页面编写一个表单
<form action="${pageContext.request.contextPath}/upload2" method="post" enctype="multipart/form-data">
选择图片:<input type="file" name="upload"><br>
<input type="submit" value="上传">
</form>
第三步:配置视图解析器
<!-- 配置文件上传解析器 -->
<bean id="multipartResolver" class="org.springframework.web.multipart.commons.CommonsMultipartResolver">
<!-- 设置上传文件的最大尺寸为 5MB -->
<property name="maxUploadSize">
<value>5242880</value>
</property>
</bean>
第四步:编写控制器
/***
* @Description 图片上传,跨服务器
* @Param: [upload]
* @return: java.lang.String
*/
@RequestMapping(path = "/upload2", method = RequestMethod.POST)
public String upload2(MultipartFile upload) throws Exception {
//上传服务器地址
String path = "http://localhost:8081/uploads/";
if (null != upload) {
//获取上传文件的全名
String oldFileName = upload.getOriginalFilename();
//截取后缀名并统一转为小写后缀名
String suffixNmae = oldFileName.substring(oldFileName.lastIndexOf(".") + 1).toLowerCase();
//随机生成一串字符作为文件名称
String newFileName = UUID.randomUUID().toString().replace("-", "") + "." + suffixNmae;
//创建客户端对象
Client client = Client.create();
//连接图片服务器
WebResource resource = client.resource(path + newFileName);
//上传图片
resource.put(upload.getBytes());
}
return "success";
}