客户端的文件上传

文件上传场景

1.通过form表单的方式(我们主要了解这一种)

2.通过JS + ajax 的方式实现

form表单方式

前端

1.<form enctype="...">  form 表单的提交方式不再是默认的 (application/x-www-urlencoded)

eg.(name1 = value1&name2 = value2)

改变为multipart/form-data,method必须是POST

2.文件上传通过<input>标签,type改变为<input type="file">

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>Title</title>
</head>
<body>
  <form method="post" action="/will404" enctype="multipart/form-data">
      <input type="file" name="image">
      <button>提交</button>
  </form>
</body>
</html>

 后端

 1.支持POST请求的动态资源

     继承 HttpServlet + @web Servlet("...") + 重写 doPost 方法

2.Servlet 规定,读取 multipart 类型的 form 数据时,必须使用@MultipartConfig 修饰类

3.使用HttpServletRequest req.getPart(...)

@MultipartConfig //这里是死规定,否则会有 500 错误
@WebServlet("/upload.do")
public class UpLoadServlet extends HttpServlet {
    @Override
    protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        Part image = req.getPart("image");
        String submittedFileName = image.getSubmittedFileName();
//        String filename = "D:\\jiaoer\\" + submittedFileName;
//        image.write(filename);
        String realPath = req.getServletContext().getRealPath("/upload");
        System.out.println(realPath);
        new File(realPath).mkdirs();
        String filename = realPath + "\\" + submittedFileName;
        image.write(filename);
        //        req.setCharacterEncoding("utf-8");
//        System.out.println(req.getParameter("username"));
//        System.out.println(req.getParameter("password"));

//        Part username = req.getPart("username");
//        System.out.println(username.getName());
//        System.out.println(username.getContentType());
//        Part password = req.getPart("password");
//        System.out.println(password.getName());
//        System.out.println(password.getContentType());
//        System.out.println("-------");

//        Part image = req.getPart("image");
//        System.out.println(image.getName());
//        System.out.println(image.getContentType());
//        System.out.println(image.getSubmittedFileName());
//        InputStream inputStream = image.getInputStream();
//        byte[] buf = new byte[1024];
//        int n = inputStream.read(buf);
//        String s = new String(buf,0,0,"UTF-8");
//        System.out.println(s);


    }
}

 

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值