Jsp页面设置:
<formaction="${pageContext.request.contextPath}/AddProdServlet" method="post" enctype="multipart/form-data">
</form>
Servlet相关操作:
//因为要传表单中的名称,以及值,所以创建map进行存放
Map<String, String> map = new HashMap<String, String>();
// 创建DiskFileItemFactory对象,设置缓冲区大小和临时文件目录
DiskFileItemFactory factory = new DiskFileItemFactory();
factory.setSizeThreshold(1024*100);
factory.setRepository(new File(this.getServletContext()
.getRealPath("/WEB-INF/tmp")));
// 使用DiskFileItemFactory 对象创建ServletFileUpload对象,并设置上传文件的大小限制。
ServletFileUpload fileUpload = new ServletFileUpload(factory);
//检查是否是正确的文件上传表单
if(!fileUpload.isMultipartContent(request))
{
throw new RuntimeException("请用正确的表单进行上传");
}
//设置单个文件上传的大小:
fileUpload.setFileSizeMax(1024 * 10204 * 5);
//设置文件上传的总大小:
fileUpload.setSizeMax(1024 * 10204 * 200);
//对上传的内容进行解析
List<FileItem> list = fileUpload.parseRequest(request);
//遍历上传的文件内容
for (FileItem item : list) {
//如果上传的内容是表单内容(也就是不带文件的内容)
if (item.isFormField()) {
//将表单中获得的名称获取
String name = item.getFieldName();
//将内容获取,内容为utf-8编码方式
String value = item.getString("utf-8");
//将名称和值放置到map中;
map.put(name, value);
} else {
//否则是带有文件的内容
String name = item.getName();
// 创建随机名称,这样能够将上传的商品图片名称唯一
String uuidName = UUID.randomUUID().toString() + name;
// 创建文件保存的物理路径
String path = this.getServletContext().getRealPath(
"/WEB-INF/upload");
//获取文件的hash值
int hashCode = uuidName.hashCode();
//将文件的hash值转换成十六进制的字符串
String hashStr = Integer.toHexString(hashCode);
// 讲获取的hashStr转换成数组
char hss[] = hashStr.toCharArray();
//初始化图片上传的目录是upload文件夹下
String imgurl= "/WEB-INF/upload";
//为了让图片上传的文件夹保存的图片均衡,遍历
for (char c : hss) {
path += "/" + c;
imgurl += "/" + c;
}
imgurl += "/" + uuidName;
//将图片url放在map中
map.put("imgurl", imgurl);
//创建文件夹
new File(path).mkdirs();
System.out.println(path);
// 文件的读写
InputStream in = item.getInputStream();
OutputStream out = new FileOutputStream(new File(path,uuidName));
IOUtils.In2Out(in, out);
IOUtils.close(in, out);
// 删除临时文件
item.delete();
PicUtils picUtils = new PicUtils(path+"/"+uuidName);
picUtils.resizeByHeight(100);
}
}
Prod prod = new Prod();
//将map中的值映射到商品中
BeanUtils.populate(prod, map);
service.addProd(prod);
//3 提示成功,返回首页
response.getWriter().write("添加商品成功!3秒回首页");
response.setHeader("Refresh", "3;url="+request.getContextPath()+"/index.jsp");
} catch (Exception e) {
e.printStackTrace();
}
Service相关操作:
public void addProd(Prod prod) {
dao.addProd(prod);
}
Dao相关操作:
//定义sql语句,插入商品名、商品价格、商品种类,商品库存,商品图片地址,商品描述
String sql = "insert into products values (null,?,?,?,?,?,?)";
QueryRunner runner = new QueryRunner(DaoUtils.getSource());
try {
runner.update(sql,prod.getName(),prod.getPrice(),prod.getCategory(),prod.getPnum(),prod.getImgurl(),prod.getDescription());
} catch (SQLException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}