文件上传
1、文件上传页面三要素
1)、表单的提交方式method一定是post
2)、表单enctype的值一定是multipart/form-data
3) 、input的类型一定是file
2、springmvc的要素
1)、需要添加两个jar commons-io.jar commons-fileupload.jar
2)、在springmvc容器中配置文件解析器
3)、绑定参数类型 MultipartFile ,参数的名字要和 input的name属性值保持一致
在springmvc中的配置
<!-- 文件上传 -->
<bean id="multipartResolver"
class="org.springframework.web.multipart.commons.CommonsMultipartResolver">
<!-- 设置上传文件的最大尺寸为5MB -->
<property name="maxUploadSize">
<value>5242880</value>
</property>
</bean>
jsp界面
<%@ page language="java" contentType="text/html; charset=UTF-8"
pageEncoding="UTF-8"%>
<%@ taglib uri="http://java.sun.com/jsp/jstl/core" prefix="c" %>
<%@ taglib uri="http://java.sun.com/jsp/jstl/fmt" prefix="fmt"%>
<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
<title>修改商品信息</title>
</head>
<body>
<!-- 上传图片是需要指定属性 enctype="multipart/form-data" -->
<!-- <form id="itemForm" action="" method="post" enctype="multipart/form-data"> -->
<form id="itemForm" enctype="multipart/form-data" action="${pageContext.request.contextPath }/updateitem.action" method="post">
<input type="hidden" name="id" value="${item.id }" /> 修改商品信息:
<table width="100%" border=1>
<tr>
<td>商品名称</td>
<td><input type="text" name="name" value="${item.name }" /></td>
</tr>
<tr>
<td>商品价格</td>
<td><input type="text" name="price" value="${item.price }" /></td>
</tr>
<tr>
<td>商品生产日期</td>
<td><input type="text" name="createtime"
value="<fmt:formatDate value="${item.createtime}" pattern="yyyy-MM-dd HH:mm:ss"/>" /></td>
</tr>
<tr>
<td>商品图片</td>
<td>
<c:if test="${item.pic !=null}">
<img src="/pic/${item.pic}" width=100 height=100/>
<br/>
</c:if>
<input type="file" name="pictureFile"/>
</td>
</tr>
<tr>
<td>商品简介</td>
<td><textarea rows="3" cols="30" name="detail">${item.detail }</textarea>
</td>
</tr>
<tr>
<td colspan="2" align="center"><input type="submit" value="提交" />
</td>
</tr>
</table>
</form>
</body>
</html>
商品修改的Java代码
// 商品修改
@RequestMapping("/updateitem")
public String updateitem(MultipartFile pictureFile,Items item,Model model) throws IllegalStateException, IOException{
String originalFilename = pictureFile.getOriginalFilename();//获取上传文件的完整名称(带扩展名)
String fileName = UUID.randomUUID().toString(); //创建一个随机数,作为即将保存图片的名字
String ext = originalFilename.substring(originalFilename.lastIndexOf(".")); //获取文件的扩展名
pictureFile.transferTo(new File("E:\\file\\"+fileName+ext)); //文件的保存
item.setPic(fileName+ext); //文件名称保持到表中
itemService.update(item);
return "redirect:list.action";
}
另外还需要配置tomcat服务器
参考的是:https://blog.csdn.net/qq_34458791/article/details/81110142
在你的tomcat服务器下,找到server.xml文件,在HOST标签下面配置
<Context crossContext="true" docBase="E:/file" path="/pic" reloadable="true"></Context>
doBase:你文件的绝对位置,path就是设置的虚拟路径