文件上传案例
前提:
一、form表单的"method"属性要设置成为”post方式“
二、form表单的“enctype”属性设置为“multipart/form-data”,默认是“x-www-form-urlencoded”
三、form表单中只要需要一个的文本选择域
文件上传分析
form表单为默认是“x-www-form-urlencoded”的时候,大多是字符串的方式传递,数据提交到后台之后,数据使用key==>value的方式存储,可以使用request.getParameter()取得
form表单为“multipart/form-data”的时候,实际就是二进制流的传输,后台就不能使用普通的string或者简单的pojo对象接受,我们在spring中使用MultipartFile类去接收参数
依赖的pom文件:
<!-- 文件上传包版本 -->
<fileupload.version>1.3.1</fileupload.version>
<commonsio.version>2.4</commonsio.version>
<commonscodec.version>1.9</commonscodec.version>
<!-- 文件上传组件依赖 -->
<dependency>
<groupId>commons-fileupload</groupId>
<artifactId>commons-fileupload</artifactId>
<version>${fileupload.version}</version>
</dependency>
<dependency>
<groupId>commons-io</groupId>
<artifactId>commons-io</artifactId>
<version>${commonsio.version}</version>
</dependency>
<dependency>
<groupId>commons-codec</groupId>
<artifactId>commons-codec</artifactId>
<version>${commonscodec.version}</version>
</dependency>
在Springmvc中配置:
<!-- 配置文件上传解析器,说明:
1.文件上传解析器bean的id属性值,必须是文件上传解析器接口名称首字母小写:multipartResolver
-->
<bean id="multipartResolver" class="org.springframework.web.multipart.commons.CommonsMultipartResolver">
<!-- Provides "maxUploadSize", "maxInMemorySize" and "defaultEncoding" settings as
* bean properties
-->
<!-- maxUploadSize:文件上传大小限制。以字节为单位。
10m=10*1024*1024
-->
<property name="maxUploadSize" value="10485760"></property>
<!-- maxInMemorySize:配置内存缓冲区的大小。以字节为单位。
4k=4*1024
-->
<property name="maxInMemorySize" value="4096"></property>
<!-- defaultEncoding:配置字符集编码 -->
<property name="defaultEncoding" value="UTF-8"></property>
</bean>
定义两个pojo
package com.itheima.project.pojo;
import java.util.Date;
/**
* @Description:用户实体类
*/
public class Customer {
//客户编号(主键)
private Integer custId;
//客户名称(公司名称)
private String custName;
//客户信息来源
private String custSource;
//客户所属行业
private String custIndustry;
//客户级别
private String custLevel;
//客户联系地址
private String custAddress;
//客户联系电话
private String custPhone;
//创建时间
private Date createrTime;
//附件信息
private FileObject fileObject;
public Integer getCustId() {
return custId;
}
public void setCustId(Integer custId) {
this.custId = custId;
}
public String getCustName() {
return custName;
}
public void setCustName(String custName) {
this.custName = custName;
}
public String getCustSource() {
return custSource;
}
public void setCustSource(String custSource) {
this.custSource = custSource;
}
public String getCustIndustry() {
return custIndustry;
}
public void setCustIndustry(String custIndustry) {
this.custIndustry = custIndustry;
}
public String getCustLevel() {
return custLevel;
}
public void setCustLevel(String custLevel) {
this.custLevel = custLevel;
}
public String getCustAddress() {
return custAddress;
}
public void setCustAddress(String custAddress) {
this.custAddress = custAddress;
}
public String getCustPhone() {
return custPhone;
}
public void setCustPhone(String custPhone) {
this.custPhone = custPhone;
}
public Date getCreaterTime() {
return createrTime;
}
public void setCreaterTime(Date createrTime) {
this.createrTime = createrTime;
}
public FileObject getFileObject() {
return fileObject;
}
public void setFileObject(FileObject fileObject) {
this.fileObject = fileObject;
}
@Override
public String toString() {
return "Customer{" +
"custId=" + custId +
", custName='" + custName + '\'' +
", custSource='" + custSource + '\'' +
", custIndustry='" + custIndustry + '\'' +
", custLevel='" + custLevel + '\'' +
", custAddress='" + custAddress + '\'' +
", custPhone='" + custPhone + '\'' +
", createrTime=" + createrTime +
", fileObject=" + fileObject +
'}';
}
}
package com.itheima.project.pojo;
import java.util.Date;
/**
* @Description:文件上传对象
*/
public class FileObject {
//主键
private Integer Id;
//业务主键
private Integer businessId;
//业务类型
private String businessType;
//访问路径
private String pathUrl;
//后缀名称
private String suffix;
//文件名称
private String fileName;
//创建时间
private Date createTime;
public Integer getId() {
return Id;
}
public void setId(Integer id) {
Id = id;
}
public Integer getBusinessId() {
return businessId;
}
public void setBusinessId(Integer businessId) {
this.businessId = businessId;
}
public String getBusinessType() {
return businessType;
}
public void setBusinessType(String businessType) {
this.businessType = businessType;
}
public String getSuffix() {
return suffix;
}
public void setSuffix(String suffix) {
this.suffix = suffix;
}
public String getPathUrl() {
return pathUrl;
}
public void setPathUrl(String pathUrl) {
this.pathUrl = pathUrl;
}
public String getFileName() {
return fileName;
}
public void setFileName(String fileName) {
this.fileName = fileName;
}
public Date getCreateTime() {
return createTime;
}
public void setCreateTime(Date createTime) {
this.createTime = createTime;
}
@Override
public String toString() {
return "FileObject{" +
"Id='" + Id + '\'' +
", businessId='" + businessId + '\'' +
", businessType='" + businessType + '\'' +
", suffix='" + suffix + '\'' +
", pathUrl='" + pathUrl + '\'' +
", fileName='" + fileName + '\'' +
", createTime=" + createTime +
'}';
}
}
FileObjectService类
package com.itheima.project.service;
import com.itheima.project.pojo.FileObject;
import org.springframework.web.multipart.MultipartFile;
/**
* @Description:文件处理业务
*/
public interface FileObjectService {
/**
* @Description
* @param multipartFile 上传对象
* @param businessId 业务主键
* @param businessType 业务类型
* @return
*/
public FileObject upLoad(MultipartFile multipartFile,Integer businessId, String businessType);
}
FileObjectServiceImpl
package com.itheima.project.service.impl;
import com.itheima.project.pojo.FileObject;
import com.itheima.project.service.FileObjectService;
import org.springframework.stereotype.Service;
import org.springframework.web.multipart.MultipartFile;
import java.io.File;
import java.io.IOException;
import java.util.Date;
import java.util.UUID;
/**
* @Description:
*/
@Service
public class FileObjectServiceImpl implements FileObjectService {
@Override
public FileObject upLoad(MultipartFile multipartFile, Integer businessId, String businessType) {
//构建文件对象
FileObject fileObject =new FileObject();
if (multipartFile==null){
return null;
}
//关联业务
fileObject.setBusinessId(businessId);
fileObject.setBusinessType(businessType);
String originalFilename = multipartFile.getOriginalFilename();
//获得后缀名
String suffix = originalFilename.substring(originalFilename.lastIndexOf("."));
//构建新文件名称
String fileName = UUID.randomUUID().toString();
//构建访问路径
String pathUrl = businessType+"/"+fileName+suffix;
//绑定请求路径
fileObject.setPathUrl(pathUrl);
//判定文件夹是否创建
File file = new File("F:/file-service/"+businessType);
if (!file.exists()){
file.mkdir();
}
//构建上传文件
file = new File("F:/file-service/" + pathUrl);
try {
//文件上传
multipartFile.transferTo(file);
fileObject.setCreateTime(new Date());
System.out.println("文件上传成功!");
return fileObject;
} catch (IOException e) {
e.printStackTrace();
System.out.println("文件上传失败!");
}
return null;
}
}
编写controller业务
package com.itheima.project.web;
import com.itheima.project.pojo.Customer;
import com.itheima.project.pojo.FileObject;
import com.itheima.project.service.FileObjectService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.propertyeditors.CustomDateEditor;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.WebDataBinder;
import org.springframework.web.bind.annotation.InitBinder;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.multipart.MultipartFile;
import java.text.SimpleDateFormat;
import java.util.Date;
/**
* @Description:用户controller
*/
@Controller
@RequestMapping("up-load")
public class UpLoadController {
@Autowired
FileObjectService fileObjectService;
public static String CUSTOMER_FILE = "customer_file";
@InitBinder
public void initBinder(WebDataBinder webDataBinder){
SimpleDateFormat dateFormat = new SimpleDateFormat("yyyy-MM-dd hh:mm:ss");
webDataBinder.registerCustomEditor(Date.class,
new CustomDateEditor(dateFormat, true));
}
/**
* @Description 跳转页面
*/
@RequestMapping(value = "to-add")
public String toAdd(){
System.out.println("去保存页面");
return "customer-add";
}
/**
* @Description 添加用户
* @param
* @return
*/
@RequestMapping(value = "add")
public String add(Customer customer, MultipartFile file,Model model){
Integer custId =1;
customer.setCustId(custId);
System.out.println("customer对象保存成功"+customer.toString());
FileObject fileObject = fileObjectService.upLoad(file, custId, CUSTOMER_FILE);
customer.setFileObject(fileObject);
model.addAttribute("customer", customer);
model.addAttribute("website", "http://127.0.0.1/file-service/");
return "customer-list";
}
}
【2.6】编辑jsp页面customer-add.jsp
<%@ page contentType="text/html;charset=UTF-8" language="java" %>
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
<title>Title</title>
</head>
<body>
customer:对象${customer}
<form method="post" enctype="multipart/form-data" action="${pageContext.request.contextPath}/up-load/add">
<table>
<tr>
<th>客户编号</th>
<td><input name="custId"></td>
</tr>
<tr>
<th>客户头像</th>
<td><input type="file" name="file"></td>
</tr>
<tr>
<th>客户名称</th>
<td><input name="custName"></td>
</tr>
<tr>
<th>信息来源</th>
<td><input name="custSource"></td>
</tr>
<tr>
<th>所属行业</th>
<td><input name="custIndustry"></td>
</tr>
<tr>
<th>客户级别</th>
<td><input name="custLevel"></td>
</tr>
<tr>
<th>联系地址</th>
<td><input name="custAddress"></td>
</tr>
<tr>
<th>联系电话</th>
<td><input name="custPhone"></td>
</tr>
<tr>
<th>创建时间</th>
<td><input name="createrTime"></td>
</tr>
<tr>
<td colspan="2">
<input type="submit" value="提交"/>
</td>
</tr>
</table>
</form>
</body>
</html>
customer-list.jsp
<%@ page contentType="text/html;charset=UTF-8" language="java" %>
<%--导入jstl标签库--%>
<%@ taglib prefix="c" uri="http://java.sun.com/jsp/jstl/core" %>
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
<title>用户列表jsp页面</title>
<style>
table {border:1px solid #000000}
table th{border:1px solid #000000}
table td{border:1px solid #000000}
</style>
</head>
<body>
<table cellpadding="0" cellspacing="0" width="80%">
<tr>
<th>编号</th>
<th>公司名称</th>
<th>信息来源</th>
<th>所属行业</th>
<th>级别</th>
<th>联系地址</th>
<th>联系电话</th>
<th>图片</th>
</tr>
<tr>
<td>${customer.custId}</td>
<td>${customer.custName}</td>
<td>${customer.custSource}</td>
<td>${customer.custIndustry}</td>
<td>${customer.custLevel}</td>
<td>${customer.custAddress}</td>
<td>${customer.custPhone}</td>
<td><img src="${website}${customer.fileObject.pathUrl}" width="80px" height="80px"></td>
</tr>
</table>
</body>
</html>