jsp实现文件上传(二)用cos组件实现文件上传

jsp表单

<%@ page language="java" pageEncoding="utf-8"%>

<html>
<head>
<title>My JSP 'index.jsp' starting page</title>
</head>

<body>
    <form action="cos.jsp" method="post" enctype="multipart/form-data">
        <input type="text" name="info1"><br> 
        <input type="text" name="info2"><br> 
        <input type="file" name="userface1"><br> 
        <input type="file" name="userface2"><br> 
        <input type="file" name="userface3"><br> 
        <input type="submit" name="mysub" value="upfile">
    </form>
</body>
</html>

cos组件实现文件上传 jsp代码

<%@ page language="java" pageEncoding="utf-8"%>
<%@ page import="java.io.File"%>
<%@ page import="com.oreilly.servlet.multipart.FilePart"%>
<%@ page import="com.oreilly.servlet.multipart.ParamPart"%>
<%@ page import="com.oreilly.servlet.multipart.Part"%>
<%@ page import="com.oreilly.servlet.multipart.MultipartParser"%>
<%
    //使用cos组件实现文件上传
    MultipartParser mp = new MultipartParser(request, 10 * 1024 * 1024);
    Part part;
    mp.setEncoding("utf-8");//取决于来源页面的编码,如果是表态的应为gbk,如果是jsp应为utf-8
    int ii = 0;
    while ((part = mp.readNextPart()) != null) {
        String name = part.getName();
        if (part.isParam()) {
            ParamPart paramPart = (ParamPart) part;
            String value = paramPart.getStringValue();
            out.println("param: name=" + name + "; value=" + value);
            System.out.println(value);
        } else if (part.isFile()) {
            FilePart filePart = (FilePart) part;
            String fileName = filePart.getFileName();
            if (fileName != null) {
                long size = filePart.writeTo(new File(this.getServletContext().getRealPath("/upload")));
                out.println("file: name=" + name + "; fileName=" + fileName +
                  ", filePath=" + filePart.getFilePath() + 
                  ", contentType=" + filePart.getContentType() + 
                  ", size=" + size);
              }else { 
                out.println("file: name=" + name + "; EMPTY");
              }
            out.print(fileName);
        }
    }
%>

--------------------------------------------------------------------------------------------------------

文件命名机制 

1.根据uuid

import java.io.File;
import java.util.UUID;

import com.oreilly.servlet.multipart.FileRenamePolicy;

public class MyUuid implements FileRenamePolicy {

    @Override
    public File rename(File f) {
        String body = UUID.randomUUID().toString();
        String ext = "";
        int pot = f.getName().lastIndexOf(".");
        if (pot != -1) {
            ext = f.getName().substring(pot);
        }
        String newName = body + ext;
        f = new File(f.getParent(), newName);
        return f;
    }

}

2.根据时间随机数

import java.io.File;
import java.util.UUID;

import com.oreilly.servlet.multipart.FileRenamePolicy;

public class MyRandom implements FileRenamePolicy {

    @Override
    public File rename(File f) {
        String body = String.valueOf(System.currentTimeMillis());
        String ext = "";
        int pot = f.getName().lastIndexOf(".");
        if (pot != -1) {
            ext = f.getName().substring(pot);
        }
        String newName = body + ext;
        f = new File(f.getParent(), newName);
        return f;
    }

}

3.上传文件并改名字

<!DOCTYPE html>
<html>
  <head>
    <meta charset="utf-8">
    <title>cc.html</title>
  </head>
  
  <body>
  <form action="cc.jsp" method="post" enctype="multipart/form-data">
  姓名:<input type="text" name="uname"><br>
 文件1:<input type="file" name="ufile1"><br>
 文件2:<input type="file" name="ufile2"><br>
 <input type="submit" value="提交">
  </form>
  
  </body>
</html>

 

<%@page import="com.MyRandom"%>
<%@ page language="java" pageEncoding="utf-8"%>
<%@ page import="com.oreilly.servlet.MultipartRequest"%>
<%@ page import="com.oreilly.servlet.multipart.DefaultFileRenamePolicy"%>
<%@ page import="com.MyUuid"%>
<%@ page import="java.io.File"%>
<%
    //使用cos组件实现文件上传
    String path = this.getServletContext().getRealPath("/upload");
    //MultipartRequest req = new MultipartRequest(request, path, "utf-8");
    //out.print(req.getParameter("uname"));
    //out.print("<hr>");
    //out.print(req.getFile("ufile1").getName());
    //out.print(req.getFile("ufile2").getName());
    
    //MultipartRequest req = new MultipartRequest(request,path,10*1024*1024,"utf-8",new MyUuid());
    MultipartRequest req = new MultipartRequest(request,path,10*1024*1024,"utf-8",new MyRandom());
    out.print(req.getFile("ufile1").getName());
    
%>

 -------------------------------------------------------------------------------------------------------

用servlet技术用cos组建实现上传下载

一、JSP页面如下:

Html代码
<body>
        <form method="POST" action="CosUploadServlet" ENCTYPE="multipart/form-data">
            <table>
                <tr><td><input type="text" name="subject" /></td></tr>
                <tr><td><input type="file" name="file1"/></td></tr>
                <tr><td><input type="file" name="file2"/></td></tr>
                <tr><td><input type="file" name="file3"/></td></tr>
                <tr><td><input type="submit" value="上传"/></td></tr>
            </table>          
          </form>
          <br/>
          <a href="CosDownloadServlet">下载</a>
    </body>

二、上传的Servlet如下:

Java代码
/**
 * 使用cos组件实现文件上传
 * 
 * @author mingxue.zhang@163.com
 * 
 */
public class CosUploadServlet extends HttpServlet {

    private static final long serialVersionUID = -9116026245071140150L;

    public void doPost(HttpServletRequest request, HttpServletResponse response)
            throws ServletException, IOException {
        File fileDir = new File(this.getServletContext()
                .getRealPath("/FileDir"));
        if (!fileDir.exists()) {
            fileDir.mkdirs();
        }
        // 设置上传文件的大小,超过这个大小 将抛出IOException异常,默认大小是1M。
        int inmaxPostSize = 10 * 1024 * 1024;
        MultipartRequest multirequest = null;
        // 上传文件重命名策略
        RenamePolicyCos myRenamePolicyCos = new RenamePolicyCos();
        try {
            // MultipartRequest()有8种构造函数!
            multirequest = new MultipartRequest(request, fileDir
                    .getAbsolutePath(), inmaxPostSize, "GBK", myRenamePolicyCos); // GBK中文编码模式上传文件
            String subject = multirequest.getParameter("subject");// 获取普通信息
            System.out.println(subject);
            Enumeration<String> filedFileNames = multirequest.getFileNames();
            String filedName = null;
            if (null != filedFileNames) {
                while (filedFileNames.hasMoreElements()) {
                    filedName = filedFileNames.nextElement();// 文件文本框的名称
                    // 获取该文件框中上传的文件,即对应到上传到服务器中的文件
                    File uploadFile = multirequest.getFile(filedName);
                    if (null != uploadFile && uploadFile.length() > 0) {
                        System.out.println(uploadFile.getName());
                        System.out.println(uploadFile.getPath());
                        System.out.println(uploadFile.length());
                    }
                    // 获取未重命名的文件名称
                    String Originalname = multirequest
                            .getOriginalFileName(filedName);
                    System.out.println(Originalname);
                }
            }

        } catch (Exception e) {
            e.printStackTrace();
        }

    }

    public void doGet(HttpServletRequest request, HttpServletResponse response)
            throws ServletException, IOException {
        this.doPost(request, response);
    }
}

Java代码

/**
 * 文件命名策略
 * 
 * @author mingxue.zhang@163.com
 * @date 2010-10-29
 */
public class RenamePolicyCos implements FileRenamePolicy {

    public File rename(File uploadFile) {
        String newName = getNewFileName(uploadFile.getName());
        File renameFile = new File(uploadFile.getParent(), newName);
        return renameFile;
    }

    private String getNewFileName(String fileName) {
        StringBuffer newName = new StringBuffer();
        if (null != fileName && !"".equals(fileName)) {
            String type = "";
            String name = "";
            if (fileName.indexOf(".") != -1) {
                type = fileName.substring(fileName.indexOf("."));
                name = fileName.substring(0, fileName.indexOf("."));
            }else{
                name = fileName;
            }
            newName.append(name);
            newName.append(getSuffix());
            newName.append(type);
        }
        return newName.toString();
    }
    
    
    private String getSuffix(){
        StringBuffer suffix = new StringBuffer("_");
        String now = new SimpleDateFormat("yyyy_MM_dd_hh_mm_ss").format(new Date());
        suffix.append(now);
        suffix.append("_");
        Random random = new Random();
        String randomValue = String.valueOf(random.nextInt(1000));
        suffix.append(randomValue);
        return suffix.toString();
    }

//    public static void main(String[] args) {
//        RenamePolicyCos my = new RenamePolicyCos();
//        System.out.println(my.getNewFileName("log.txt"));
//    }

}

三、下载的Servlet如下:

java代码

/**
 * 使用cos组件实现文件下载
 * 
 * @author mingxue.zhang@163.com
 * @date 2010-10-29
 */
public class CosDownloadServlet extends HttpServlet {

    public void doGet(HttpServletRequest request, HttpServletResponse response)
            throws ServletException, IOException {
        this.doPost(request, response);
    }

    public void doPost(HttpServletRequest request, HttpServletResponse response)
            throws ServletException, IOException {
        String filePath = "D:\\Tomcat\\apache-tomcat-6.0.26\\webapps\\CosUpload\\FileDir\\";
        String fileName = "2010年10月安排_2010_10_29_04_52_06_178.txt";
        String Originalname = "2010年10月安排.txt";
        String isofilename = new String(Originalname.getBytes("gb2312"),
                "ISO8859-1");
        response.setContentType("application/octet-stream");
        response.setHeader("Content-Disposition", "attachment; filename="
                + isofilename);
        ServletOutputStream out = null;
        try {
            out = response.getOutputStream();
            ServletUtils.returnFile(filePath + fileName, out);
        } catch (Exception e) {
            e.printStackTrace();
        } finally {
            if (null != out) {
                out.close();
            }
        }
    }

}

关于Servlet配置如下:

Xml代码 
<servlet>
        <servlet-name>CosUploadServlet</servlet-name>
        <servlet-class>com.mengya.servlet.CosUploadServlet</servlet-class>
    </servlet>
    <servlet>
        <servlet-name>CosDownloadServlet</servlet-name>
        <servlet-class>com.mengya.servlet.CosDownloadServlet</servlet-class>
    </servlet>


    <servlet-mapping>
        <servlet-name>CosUploadServlet</servlet-name>
        <url-pattern>/CosUploadServlet</url-pattern>
    </servlet-mapping>
    <servlet-mapping>
        <servlet-name>CosDownloadServlet</servlet-name>
        <url-pattern>/CosDownloadServlet</url-pattern>
    </servlet-mapping>

 

转载于:https://www.cnblogs.com/Dreamlu/p/4151312.html

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值