Java Web中在不使用第三方jar的情况下如何使用servlet 上传文件呢?
(1)上传表单,文件名为upload_servlet.jsp,内容如下:
- <?xml version="1.0" encoding="UTF-8" ?>
- <%@ page language="java" contentType="text/html; charset=UTF-8"
- pageEncoding="UTF-8"%>
- <%
- String path = request.getContextPath();
- String basePath = request.getScheme() + "://"
- + request.getServerName() + ":" + request.getServerPort()
- + path + "/";
- %>
- <%@ taglib prefix="s" uri="/struts-tags"%>
- <!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
- <html xmlns="http://www.w3.org/1999/xhtml">
- <head>
- <meta http-equiv="Content-Type" content="text/html; charset=UTF-8" />
- <title>servlet upload file</title>
- </head>
- <body>
- <center>
- <form action="<%=basePath %>servlet/upload.servlet" enctype="multipart/form-data"
- method="post" >
- <input type="file" name="file2" />
- <br />
- <input type="submit" value="上传" />
- </form>
- <br />
- <a href="../index.jsp">index</a>
- </center>
- </body>
- </html>
注意:上传文件表单必须指定 enctype="multipart/form-data" 和method="post"
(2)后台servlet,名称是UploadFileServlet,代码如下:
- package com.shop.jn.web.servlet;
- import java.io.File;
- import java.io.IOException;
- import java.util.Enumeration;
- import javax.servlet.ServletException;
- import javax.servlet.http.HttpServletRequest;
- import javax.servlet.http.HttpServletResponse;
- import org.apache.struts2.dispatcher.multipart.MultiPartRequestWrapper;
- import com.common.util.SystemHWUtil;
- import com.common.web.servlet.upload.SUploadServlet;
- /**
- * Servlet implementation class UploadFileServlet
- */
- public class UploadFileServlet extends SUploadServlet {
- private static final long serialVersionUID = 1L;
- protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
- doPost(request, response);
- }
- protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
- System.out.println("UploadFileServlet");
- if(request instanceof MultiPartRequestWrapper){
- MultiPartRequestWrapper mp=(MultiPartRequestWrapper)request;
- Enumeration<String> multi=mp.getFileParameterNames();
- String formFileTagName=null;//"file2"
- for( ;multi.hasMoreElements();){
- String element=multi.nextElement();
- formFileTagName=element;//表单中标签的名称:file标签的名称
- break;
- }
- String fileName=mp.getFileNames(formFileTagName)[0];//上传的文件名
- //保存到哪儿
- File savedFile=super.getUploadedFilePath(request, "upload", fileName);//D:\eclipse\workspace\shop_goods\ upload
- File[]files=mp.getFiles(formFileTagName);
- File uploadFile=files[0];//上传的文件
- SystemHWUtil.copyFile(uploadFile, savedFile/*new File("D:\\Temp\\a\\a\\c.zip")*/);
- uploadFile.delete();
- }
- response.sendRedirect("../upload_download/upload_servlet.jsp");
- }
- }
说明:上传的文件保存到项目根目录下的upload文件夹中。
注意:上述servlet只能处理单文件上传。
servlet在web.xml中的配置如下:
- <servlet>
- <servlet-name>UploadFileServlet</servlet-name>
- <servlet-class>com.shop.jn.web.servlet.UploadFileServlet</servlet-class>
- </servlet>
- <servlet-mapping>
- <servlet-name>UploadFileServlet</servlet-name>
- <url-pattern>/servlet/upload.servlet</url-pattern>
- </servlet-mapping>
UploadFileServlet 中使用的方法的源码
SystemHWUtil.copyFile(jar io0007-find_progess_中的类com.common.util.SystemHWUtil):
- /**
- *
- * @param srcFile
- * :must be regular file,can not be folder;
- * @param targetFile
- * :must be regular file,can not be folder;
- * @throws IOException
- */
- public static void copyFile(File srcFile, File targetFile)
- throws IOException {
- FileInputStream in = new FileInputStream(srcFile);
- FileOutputStream out = new FileOutputStream(targetFile);
- copyFile(in, out);
- }
- public static void copyFile(InputStream in, FileOutputStream target)
- throws IOException {
- // File targetFile = new File(targetFileName);
- // FileOutputStream target = null;
- // if (targetFile.isDirectory())
- // {
- // targetFile = new File(targetFile, simpleName);
- // }
- try {
- // target = new FileOutputStream(targetFile);
- byte[] buffer = new byte[BUFF_SIZE];
- int byteNum;
- while ((byteNum = in.read(buffer)) != NEGATIVE_ONE) {
- target.write(buffer, 0, byteNum);
- }
- System.out.println("[SystemUtil:copyFile]:file copy successfully!");
- } catch (Exception e) {
- e.printStackTrace();
- } finally {
- if (in != null) {
- in.close();
- in = null;
- }
- if (target != null) {
- target.close();
- target = null;
- }
- }
- }
WebServletUtil.getUploadedPath(jar io0007-find_progess_中的类com.common.util.WebServletUtil):
- /***
- * java web //
- * D:\xxx\eclipse\workspace\.metadata\.plugins\org.eclipse.wst.server
- * .core\tmp0\wtpwebapps\shop_goods\images //
- * D:\xxx\eclipse\workspace\shop_goods\ upload
- *
- * @param uploadFolderName
- * @param projectName
- * @param sContext
- * @return
- */
- public static String getUploadedPath(String uploadFolderName,
- String projectName, ServletContext sContext) {
- String uploadFolder_tmp = null;
- if (uploadFolderName.startsWith("/")) {
- uploadFolder_tmp = uploadFolderName;
- } else {
- uploadFolder_tmp = "/" + uploadFolderName;// "/upload"
- }
- String realpath = sContext.getRealPath(uploadFolder_tmp);
- // project name ,eg.shop_goods
- projectName = SystemHWUtil.deleteFrontSlash(projectName);
- realpath = SystemHWUtil.getRealPath(realpath, projectName);
- return realpath;
- }
注意:
(1)使用的容器是tomcat,不是jetty;
(2)没有使用第三方上传jar包