在开发中常常需要上传文件,上传文件的方式有很多种,这里有一个cos实现的例子。
首先是要拷贝cos.jar包拷贝到WEB-INF/lib目录下,然后才进行编码。
创建一个可以进行自动重命名的Java文件FileRenameUtil.java:
- package org.ml.drp.util;
- import java.io.File;
- import java.util.Date;
- import com.oreilly.servlet.multipart.FileRenamePolicy;
- /**
- * 文件重命名
- * @author MuLing
- *
- */
- public class FileRenameUtil implements FileRenamePolicy {
- public File rename(File file) {
- String body = "";
- String ext = "";
- Date date = new Date();
- int pot = file.getName().lastIndexOf(".");//取得文件名和后缀分割点
- if (pot != -1) {//说明后缀存在
- body = date.getTime() + "";//采用时间的形式命名
- ext = file.getName().substring(pot);//截取后缀名
- } else {
- body = (new Date()).getTime() + "";
- ext = "";
- }
- String newName = body + ext;
- file = new File(file.getParent(), newName);//对文件进行重命名
- return file;
- }
- }
然后创建一个实现上传功能的servlet,为了方便查看上传情况,所以加入了一些输出语句。
FileUploadServlet.java
- package org.ml.servlet;
- import java.io.File;
- import java.io.IOException;
- import java.util.Enumeration;
- import javax.servlet.ServletException;
- import javax.servlet.http.HttpServlet;
- import javax.servlet.http.HttpServletRequest;
- import javax.servlet.http.HttpServletResponse;
- import com.oreilly.servlet.MultipartRequest;
- /**
- * 能够进行文件上传的servlet类
- * @author MuLing
- *
- */
- public class UploadServlet extends HttpServlet {
- private static final long serialVersionUID = 1L;
- public UploadServlet() {
- super();
- }
- public void destroy() {
- super.destroy();
- }
- @SuppressWarnings("unchecked")
- public void doGet(HttpServletRequest request, HttpServletResponse response)
- throws ServletException, IOException {
- // 存绝对路径
- // String filePath = "C://upload";
- // 存相对路径
- String filePath = getServletContext().getRealPath("/") + "upload";
- System.out.println(filePath);//输出存放上传文件所到的路径
- File uploadPath = new File(filePath);
- // 检查文件夹是否存在 不存在 创建一个
- if (!uploadPath.exists()) {
- uploadPath.mkdir();
- }
- // 文件最大容量 3M
- int fileMaxSize = 3 * 1024 * 1024;
- // 存放文件描述
- @SuppressWarnings("unused")
- String[] fileDiscription = { null, null };
- // 文件名
- String fileName = null;
- // 上传文件数
- int fileCount = 0;
- // 重命名策略
- RandomFileRenamePolicy rfrp = new RandomFileRenamePolicy();
- // 上传文件
- MultipartRequest mulit = new MultipartRequest(request, filePath,
- fileMaxSize, "UTF-8", rfrp);//取得上传文件
- String userName = mulit.getParameter("userName");
- System.out.println(userName);
- Enumeration filesname = mulit.getFileNames();//取得上传的所有文件(相当于标识)
- while (filesname.hasMoreElements()) {
- String name = (String) filesname.nextElement();//标识
- System.out.println(name);
- fileName = mulit.getFilesystemName(name); //取得文件名
- String contentType = mulit.getContentType(name);//工具标识取得的文件类型
- if (fileName != null) {
- fileCount++;
- }
- System.out.println("文件名:" + fileName);
- System.out.println("文件类型: " + contentType);
- }
- System.out.println("共上传" + fileCount + "个文件!");
- }
- public void doPost(HttpServletRequest request, HttpServletResponse response)
- throws ServletException, IOException {
- this.doGet(request, response);
- }
- public void init() throws ServletException {
- }
- }
在web.xml文件中的配置servlet如下:
- <?xml version="1.0" encoding="UTF-8"?>
- <web-app version="2.5"
- xmlns="http://java.sun.com/xml/ns/javaee"
- xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
- xsi:schemaLocation="http://java.sun.com/xml/ns/javaee
- http://java.sun.com/xml/ns/javaee/web-app_2_5.xsd">
- <servlet>
- <servlet-name>UploadServlet</servlet-name>
- <servlet-class>org.ml.servlet.UploadServlet</servlet-class>
- </servlet>
- <servlet-mapping>
- <servlet-name>UploadServlet</servlet-name>
- <url-pattern>/UploadServlet</url-pattern>
- </servlet-mapping>
- <welcome-file-list>
- <welcome-file>index.jsp</welcome-file>
- </welcome-file-list>
- </web-app>
上传页面代码如下:
- <%@ page language="java" import="java.util.*" 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>
- </head>
- <body>
- <form enctype="multipart/form-data" method = "post" action = "UploadServlet">
- <input type="text" name="userName" />
- <p>上传文件1:<input type = "file" name = "File1" size = "20" maxlength = "20"><br></p>
- <p>上传文件2:<input type = "file" name = "File2" size = "20" maxlength = "20"><br></p>
- <p>上传文件3:<input type = "file" name = "File3" size = "20" maxlength = "20"><br></p>
- <p>上传文件4:<input type = "file" name = "File4" size = "20" maxlength = "20"><br></p>
- <input type = "submit" value = "上传">
- </form>
- </body>
- </html>
注明:本代码是摘抄代码,所有权归 cselmu9 所有!