温馨提示×

温馨提示×

您好,登录后才能下订单哦!

密码登录×
登录注册×
其他方式登录
点击 登录注册 即表示同意《亿速云用户服务条款》

servlet3.0文件上传

发布时间:2020-05-01 04:26:47 来源:网络 阅读:742 作者:奔跑吧爽爽 栏目:开发技术

1.浏览器端:选择图片、提交表单,同时将图片发送给服务器
<form action=”” method=”post” enctype=”multipart/form-data”>
<input type=”file” name=”image”>
<input type=”submit”>
上传的内容,都在请求体中。
2.服务器端:
1)手动获得请求体,需要手动解析。request.getInputStream()
2)使用servlet3.0
3)第三方工具 – apache-commons-fileupload
4)struts2
servlet3.0文件上传

@WebServlet("/FileUploadServlet")
@MultipartConfig        //表示支持文件上传,否则获得null

public class FileUploadServlet extends HttpServlet {
    private static final long serialVersionUID = 1L;

protected void doGet(HttpServletRequest request, HttpServletResponse response) 
        throws ServletException, IOException {
    //1 普通字段
    String username = request.getParameter("username");
    System.out.println(username);

    //2 上传字段
    Part part = request.getPart("image");
    //2.1 获得文件名   
    // * IE         --> C:\Users\liangtong\Desktop\heima.txt
    // * 其他浏览器  --> heima.txt
    String contentDisposition = part.getHeader("Content-Disposition");
    System.out.println(contentDisposition);
    // * 截取文件名
    int start = contentDisposition.indexOf("filename=") + 10;
    int end = contentDisposition.length() - 1;
    String fileName = contentDisposition.substring(start, end);

    // * 浏览器兼容  -- lastIndexOf() 如果没有获得返回 -1
    fileName = fileName.substring( fileName.lastIndexOf("\\") + 1);

    System.out.println(fileName);

    //2.2 获得上传文件内容
    InputStream is = part.getInputStream();

    //2.3 将流写入到服务器文件中
    // * 上传目录
    String dir = this.getServletContext().getRealPath("/WEB-INF/upload");
    File file = new File(dir , fileName);

    // * 流的对拷
    FileOutputStream out = new FileOutputStream(file);

    byte[] buf = new byte[1024];
    int len = -1;
    while( (len = is.read(buf)) != -1 ){
        out.write(buf, 0, len);
    }

    out.close();
    is.close();

}

protected void doPost(HttpServletRequest request, HttpServletResponse response) 
        throws ServletException, IOException {
    doGet(request, response);
}
向AI问一下细节

免责声明:本站发布的内容(图片、视频和文字)以原创、转载和分享为主,文章观点不代表本网站立场,如果涉及侵权请联系站长邮箱:is@yisu.com进行举报,并提供相关证据,一经查实,将立刻删除涉嫌侵权内容。

AI