我使用了一个cos组件,将cos.jar包拷贝到lib下

新建一个jsp页面 dcumentUpload.jsp


<%@ page language="java" contentType="text/html; charset=UTF-8" 
    pageEncoding="UTF-8"%> 
 
 
 
 
文档上传 
 
          
 
 
请上传要处理的文件,过程可能需要几分钟,请稍候片刻。




然后再建一个servlet来处理文件上传

package ytu.botao.servlet;
import java.io.File;
import java.io.IOException;
import java.io.PrintWriter;
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;
import com.oreilly.servlet.multipart.DefaultFileRenamePolicy;
public class DoUploadServlet extends HttpServlet {
    public void doGet(HttpServletRequest request, HttpServletResponse response)
            throws ServletException, IOException {
        process(request, response);
    }
    public void doPost(HttpServletRequest request, HttpServletResponse response)
            throws ServletException, IOException {
        process(request, response);
    }
    public void process(HttpServletRequest request, HttpServletResponse response)
            throws ServletException, IOException {
        response.setContentType("text/html");
        PrintWriter out = response.getWriter();
        // 文件上传采用cos组件上传,可更换为commons-fileupload上传,文件上传后,保存在upload文件夹
        // 获取文件上传路径
        String saveDirectory = getServletContext().getRealPath("/")
                + "resource";
        // 打印上传路径信息
        System.out.println(saveDirectory);
        // 每个文件最大50m
        int maxPostSize = 50 * 1024 * 1024;
        // 采用cos缺省的命名策略,重名后加1,2,3...如果不加dfp重名将覆盖
        DefaultFileRenamePolicy dfp = new DefaultFileRenamePolicy();
        // response的编码为"UTF-8",同时采用缺省的文件名冲突解决策略,实现上传,如果不加dfp重名将覆盖
        MultipartRequest multi = new MultipartRequest(request, saveDirectory,
                maxPostSize, "UTF-8", dfp);
        // 输出反馈信息
        Enumeration files = multi.getFileNames();
        while (files.hasMoreElements()) {
            System.err.println("ccc");
            String name = (String) files.nextElement();
            File f = multi.getFile(name);
            if (f != null) {
                // ----------打开文件所放文件夹 取出文件名字
                String fileName = multi.getFilesystemName(name);
                // 获取上传文件的扩展名
                String extName = fileName
                        .substring(fileName.lastIndexOf(".") + 1);
                // 文件全路径
                String lastFileName = saveDirectory + "\\" + fileName;
                // 获取需要转换的文件名,将路径名中的'\'替换为'/'
                String converfilename = saveDirectory.replaceAll("\\\\", "/")
                        + "/" + fileName;
                System.out.println("需要转换的文件:" + converfilename);
//              response.setContentType(arg0)
                out.print("上传完成................");
            }
        }
    }
}