Servlet文件上传

xiaoxiao2021-02-28  114

注意:不能使用 继承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); } }

转载请注明原文地址: https://www.6miu.com/read-24412.html

最新回复(0)