使用jsp和serlvet来实现最简单的上传,供大家参考,具体内容如下
1、页面index.jsp
<%@ page language="java" pageEncoding="UTF-8"%> <% String path = request.getContextPath(); String basePath = request.getScheme()+"://"+request.getServerName()+":"+request.getServerPort()+path+"/"; %> <!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN"> <html> <head> <base href="<%=basePath%>"> <title>index.jsp</title> <meta http-equiv="pragma" content="no-cache"> <meta http-equiv="cache-control" content="no-cache"> <meta http-equiv="expires" content="0"> </head> <body> <form action="upload" method="post" enctype="multipart/form-data"> <br> 姓名:<input type="text" name="uname"/> <br> 上传文件:<input type="file" name="pic"/> <br> <input type="submit" value="提交"></input> </form> </body> </html>
2、action跳转到了upload的servlet,所以要web.xml里面配置,web.xml:
<?xml version="1.0" encoding="UTF-8"?> <web-app version="2.5" xmlns="http://java.sun.com/xml/ns/javaee" xmlns:xsi="http://.soft4j.httpupload4j.SmartUploadException; public class SmartuploadAction extends HttpServlet { private static final long serialVersionUID = -8610555375032925108L; @Override protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException { req.setCharacterEncoding("utf-8"); resp.setCharacterEncoding("utf-8"); SmartUpload su = new SmartUpload(); // 由于multipart/form-data的传输原因导致req不能使用,所以使用smartupload产生的request Request reqest = su.getRequest(); // 获得pageContext对象 PageContext pageContext = JspFactory.getDefaultFactory() .getPageContext(this, req, resp, null, true, 8192, true); su.initialize(pageContext); try { su.upload(); // 上传到本项目的upload目录 su.save("upload"); } catch (SmartUploadException e) { e.printStackTrace(); } // 使用smartupload产生的reqest对象来获得页面传递的参数 String uname = reqest.getParameter("uname"); System.out.println(uname); } }
最后说明:使用的组件包为smartupload.zip。
以上就是本文的全部内容,希望对大家的学习有所帮助,也希望大家多多支持。