分享web开发知识

注册/登录|最近发布|今日推荐

主页 IT知识网页技术软件开发前端开发代码编程运营维护技术分享教程案例
当前位置:首页 > 运营维护

servlet3.0文件上传

发布时间:2023-09-06 01:44责任编辑:董明明关键词:文件上传
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

@WebServlet("/FileUploadServlet")@MultipartConfig ???????//表示支持文件上传,否则获得nullpublic 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);}

servlet3.0文件上传

原文地址:http://blog.51cto.com/13579086/2083445

知识推荐

我的编程学习网——分享web前端后端开发技术知识。 垃圾信息处理邮箱 tousu563@163.com 网站地图
icp备案号 闽ICP备2023006418号-8 不良信息举报平台 互联网安全管理备案 Copyright 2023 www.wodecom.cn All Rights Reserved