Servlet文件上传

注意:不能使用 继承BaseServlet形式

1.页面表单三要素:

a. method="post"

b. 必须有上传组件

c. 必须是上传表单

 

2.文件上传三步(使用工具)

导包:

commons-fileupload-xxx

commons-io-xxx

//1. 创建磁盘文件工厂

DiskFileItemFactory factory = new DiskFileItemFactory();

//2. 创建 上传组件核心类用来解析request的字节流

ServletFileUpload upload = new ServletFileUpload(factory);

//3. 用核心类解析request的字节流(一个对象封装着一个表单输入项的信息)

List list = new upload.parseRequest(request);

 

3.FileItem

isFormField();  返回boolean true:普通表单项 false:文件上传项

getFieldName(); 返回String 表单输入项的 name属性

getString(String encoding); 返回String 只 返回普通表单项的参数,encoding是编码

getInputStream(); 返回InputStream,只返回文件上传项的文件内容

delete(); 会删除上传产生的临时文件

getName(); 返回String,返回的是上传组件的文件名

火狐:文件名.扩展名

IE和一些浏览器:绝对路径+文件名.扩展名

 

4.文件上传代码实现

A:上传三步,看 2

B:遍历集合

普通项,保存到map中(设置编码)

上传项:

1. 获取文件想要上传的真实路径

2. 获取要上传文件的名字

3. 获取文件的输入流

4. 获取输出流

5. 流的对拷

6. 关闭流资源

C:封装数据到商品对象product

map集合中的数据 /以及需要单独封装的数据

D:调用service层 将商品对象product写入数据库

E:重定向到业务需求的下一页面

 

5.完整doGet(xxx,xxx)代码

	public void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
		response.setContentType("text/html;charset=utf-8");
		request.setCharacterEncoding("utf-8");// 中文乱码\
		HashMap map = new HashMap<>();
		InputStream is = null;
		OutputStream os = null;
		DiskFileItemFactory factory = new DiskFileItemFactory();
		ServletFileUpload upload = new ServletFileUpload(factory);
		try {
			String realPath = null;
			String name = null;
			List fileItem = upload.parseRequest(request);
			if (fileItem != null && fileItem.size() > 0) {
				for (FileItem fileItem1 : fileItem) {
					if (fileItem1.isFormField()) {
						map.put(fileItem1.getFieldName(), fileItem1.getString("utf-8"));
					} else {
						is = fileItem1.getInputStream();
						realPath = request.getServletContext().getRealPath("/products/1");
						name = fileItem1.getName();
						os = new FileOutputStream(new File(realPath + "/" + name));
						IOUtils.copy(is, os);
						is.close();
						os.close();
					}
				}
			}
			Product product = new Product();
			BeanUtils.populate(product, map);
			product.setPid(UUIDUtils.getUUID());
			product.setPdate(new Date());
			product.setPflag(0);
			product.setPimage("products/1/" + name);
			IProductService service = new ProductServiceImpl();
			String cid = (String) map.get("cid");
			Category category = service.findCategoryByCId(cid);
			product.setCategory(category);
			service.addProductForBack(product);
			response.sendRedirect(request.getContextPath() + "/index.jsp");
		} catch (Exception e) {
			throw new RuntimeException(e);
		}
	}


  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值