当前位置:K88软件开发文章中心编程全书编程全书03 → 文章内容

Servlet 文件上传

减小字体 增大字体 作者:佚名  来源:网上搜集  发布时间:2019-1-11 13:13:44

parator + fileName; File storeFile = new File(filePath); // 在控制台输出文件的上传路径 System.out.println(filePath); // 保存文件到硬盘 item.write(storeFile); request.setAttribute("message", "文件上传成功!"); } } } } catch (Exception ex) { request.setAttribute("message", "错误信息:





" + ex.getMessage()); } // 跳转到 message.jsp request.getServletContext().getRequestDispatcher("/message.jsp").forward( request, response); }}message.jsp 文件代码如下:<%@ page language="java" contentType="text/html; charset=UTF-8" pageEncoding="UTF-8"%><!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http:





//www.w3.org/TR/html4/loose.dtd"><html><head><meta http-equiv="Content-Type" content="text/html; charset=UTF-8"><title>文件上传结果</title></head><body> <center> <h2>${message}</h2> </center></body></html>编译和运行 Servlet编译上面的 Servlet UploadServlet,并在 web.xml 文件中创建所需的条目,如下所示:<?xml version="1.0" encoding="UTF-8"?><web-app xmlns:





xsi="http:





//www.w3.org/2001/XMLSchema-instance" xmlns="http:





//java.sun.com/xml/ns/javaee" xmlns:





web="http:





//java.sun.com/xml/ns/javaee/web-app_2_5.xsd" xsi:





schemaLocation="http:





//java.sun.com/xml/ns/javaee http:





//java.sun.com/xml/ns/javaee/web-app_2_5.xsd" id="WebApp_ID" version="2.5"> <servlet> <display-name>UploadServlet</display-name> <servlet-name>UploadServlet</servlet-name> <servlet-class>com.k88.test.UploadServlet</servlet-class> </servlet> <servlet-mapping> <servlet-name>UploadServlet</servlet-name> <url-pattern>/TomcatTest/UploadServlet</url-pattern> </servlet-mapping></web-app>现在尝试使用您在上面创建的 HTML 表单来上传文件。当您在浏览器中访问:http:





//localhost:





8080/TomcatTest/upload.jsp ,演示如下所示:

上一页  [1] [2] 


Servlet 文件上传