文件上传

多文件上传的要求:

1:完成文件上传

  1:将上传的文件统一放置到upload的文件夹下

  2:将每天上传的文件,使用日期格式的文件夹分开,将每个业务的模块放置统一文件夹下

  3:上传的文件名要指定唯一,可以使用UUID的方式,也可以使用日期作为文件名

  4:封装一个文件上传的方法,该方法可以支持多文件的上传,即支持各种格式文件的上传

  5:保存路径path的时候,使用相对路径进行保存,这样便于项目的可移植性

 

第一步:在util包下封装一个方法:

public class FileUploadUtils {

 

    //完成文件上传,同时返回上传文件的路径path(相对路径)

    /**

     * 完成文件上传

          1:将上传的文件统一放置到upload的文件夹下

          2:将每天上传的文件,使用日期格式的文件夹分开,并使得每个业务模块用文件夹的方式分开

          3:上传的文件名要指定唯一,可以使用UUID的方式,也可以使用日期作为文件名

          4:封装一个文件上传的方法,该方法可以支持多文件的上传,即支持各种格式文件的上传

          5:保存路径path的时候,使用相对路径进行保存,这样便于项目的可移植性

 

     */

    public static String fileUploadReturnPath(File upload, String uploadFileName,String model) {

        //获取upload的文件夹

        String basepath = ServletActionContext.getServletContext().getRealPath("/upload");

        //指定日期格式的文件夹(yyyy/MM/dd

        String datepath = DateUtils.dateToString(new Date());

        //文件后缀

        String perfix = uploadFileName.substring(uploadFileName.lastIndexOf("."));

        //文件名(格式:ADFSDFSDFA@#$@#$@DSDFS12321.doc)

        String filename = UUID.randomUUID().toString()+perfix;

       

        //判断当前日期文件夹是否存在,如果不存在,创建一个日期的文件夹

        String modelPath = basepath+datepath+model;

        File dateFile = new File(modelPath);

        if(!dateFile.exists()){

            dateFile.mkdirs();

        }

       

        //目标文件

        File destFile = new File(modelPath+"/"+filename);  

        //文件上传

        upload.renameTo(destFile);

        //返回相对路径

        return "/upload"+ datepath+model+"/"+filename;

    }

    public static void main(String[] args) throws Exception {

        //文件上传

        //方案一:(复制,粘贴)

        //源文件

        File srcFile = new File("F:\\dir\\a.txt");

        //目标文件

        File destFile = new File("F:\\dir\\dir2xxxxxxxxxxx\\a.txt");

        //FileUtils.copyFile(srcFile, destFile);

       

        //方案二:(剪切)

        boolean flag = srcFile.renameTo(destFile);

        System.out.println(flag);

    }

 

}

 

第二步:jsp页面的表单要求:

并且表单提交:

<form name="Form1"

action="${pageContext.request.contextPath }/workflow/elecApplicationTemplateAction_save.do" method="post" enctype="multipart/form-data">

         <s:file name="upload" id="upload" cssStyle="width:450px;"></s:file> *

</form>

 

第三步:文件上传的要求:

在VO对象中:

//获取文件类型的upload

    private File [] upload;

    //文件类型

    private String [] uploadContentType;

    //文件名

    private String [] uploadFileName;

其中upload表示页面提交的文件:

uploadContentType表示获取上传文件的类型

uploadFileName表示获取上传文件的名称

<s:file name="upload" id="upload" cssStyle="width:450px;"></s:file> *

 

这里注意:如果是单文件上传,就是File类型的对象

            如果是多文件上传,就是File类型的数组对象

posted @ 2016-07-18 19:31  kimi9py  阅读(182)  评论(0编辑  收藏  举报