1.概述
通常浏览器上传的所有参数,我们可以通过request对象的getParameter , getParameterMap , getParameterValue 这三个方法拿到所有的请求参数,
但有一种情况,当强求包含参数包含文件上传时, 这三个方法都失效,无法拿到参数,
我们就需要request对象的getInputStream方法获取这些参数, 如何解析这个字节输入流呢?
apache 软件基金会: 开发了工具fileupload工具, 专门解析字节输入流,实现文件上传功能.
2. 先导入jar包
打开pom文件, 加入fileupload的jar包依赖.
2.2 三要素
- 必须post请求
- form表单属性必须包含 enctype=“multipart/form-data”
- 上传文本框input type=“file” , 必须有name属性
2.3 代码逻辑
自定义一个parseRequest(request)方法, 返回map集合,map集合中封装了商品添加功能中提交所有的数据;
使用BeanUtils.populate(product,parameterMap)方法将map集合封装到product对象中; 调用业务层addProduct方法传递product对象参数,在dao层将新添加的商品写入数据库;
protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
Map<String, String[]> parameterMap = parseRequest(request); //request.getParameterMap();
Product product = new Product();
try {
BeanUtils.populate(product,parameterMap);
} catch (Exception e) {
e.printStackTrace();
}
productService.addProduct(product);
ResultVO resultVO = new ResultVO(ResultVO.SUCCESS,null,"商品添加成功");
response.getWriter().print(objectMapper.writeValueAsString(resultVO));
}