Web实现文件上传代码

web中创建一个upload包用来存放图片

 out里可以查看

jsp文件代码

<%@ page contentType="text/html;charset=UTF-8" language="java" %>
<html>
<head>
    <title>Title</title>
</head>
<body>
<!--如果表单中有文件要提交就一定要加enctype-->
<form action="Do_Fileupload" method="post" enctype="multipart/form-data">
    用户名<input type="text" name="uname"/><br/>
    密码<input type="text" name="upwd"/><br/>
    请选择头像<input type="file" name="file"/>
    <input type="submit" value="登录"/>
</form>
</body>
</html>

效果:

 

 

 Serlvet文件代码

package Servlet;

import javax.servlet.ServletException;
import javax.servlet.annotation.MultipartConfig;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.Part;
import java.io.IOException;
@WebServlet("/Do_Fileupload")
@MultipartConfig(maxFileSize = 1024*1024*2)     //maxFileSize设置上传大小
public class Do_Fileupload extends HttpServlet {
    //读取注解中的最大限制
    private static MultipartConfig config=Do_Fileupload.class.getAnnotation(MultipartConfig.class);


    @Override
    protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        super.doGet(req, resp);
    }

    @Override
    protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
      String uname=req.getParameter("uname");
      String upwd=req.getParameter("upwd");
        System.out.println(uname+"~~"+upwd);
        //servlet3.0提供的part接受
        Part p=req.getPart("file");
        //设置上传路径到upload
        String path=req.getSession().getServletContext().getRealPath("upload");
        //开始上传  getSubmittedFileName()需要基于Tomcat8.0以上
        p.write(path+"\\"+p.getSubmittedFileName());

        String message="目前文件大小"+p.getSize();
        System.out.println(message+"目前文件允许大小"+config.maxFileSize());

        //将上传的文件名上传到session
        req.getSession().setAttribute("fname",p.getSubmittedFileName());


        resp.sendRedirect("file.jsp");
        //控制台输出路径
        System.out.println(path+"\\"+p.getSubmittedFileName());

    }
}

结果

 

 

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值