文件上传

/*
 * @Description //TODO  文件上传
 * @Date 2019/11/26 16:36
 * @Param
 * @return
 **/
//1.在接收请求的Servlet上添加 @MultipartConfig 注解,标识该Servlet会接收文件内容;
@MultipartConfig
@WebServlet("/fileServlet1")
public class FileServlet1 extends HttpServlet {
    protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        request.setCharacterEncoding("utf-8");//解决post请求乱码

       //2.通过 request.getPart("文件参数名") 得到一个Part对象,该对象封装了文件表单项相关的所有内容;
        Part file = request.getPart("file");
        //3.通过 part对象.getSubmittedFileName() 可以得到文件的名称;
        String subName = file.getSubmittedFileName();
        //4.通过 part对象.getInputStream() 可以得到流对象,读取文件的内容;
        InputStream fis = file.getInputStream();

        //创建保存的文件夹
        File srcFile = new File("C:\\Users\\Desktop\\upload");
        if (!srcFile.exists()) {
            srcFile.mkdirs();
        }

        //5.通过 输出流,把文件的内容输出到服务器本地文件中。
        FileOutputStream fos = new FileOutputStream(srcFile+"/"+subName);
        byte[] by = new byte[1024];
        int len;
        while ((len = fis.read(by)) != -1) {
            fos.write(by, 0, len);
        }
        fos.close();


    }

html代码

<body>
<!--文件上传三要素   必须是post请求   enctype="multipart/form-data"   type 必须是 file 属性-->
<form method="post" enctype="multipart/form-data" action="/fileServlet1">
  姓名<input type="text" name="username"> <br>
  文件<input type="file" name="file"><br>
  <input type="submit" value="提交">
</form>
</body>
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值