文件上传

来源:互联网 发布:国外留学 美食 知乎 编辑:程序博客网 时间:2024/05/29 12:25

利用struts2进行文件上传,首先要知道文件上传的前提:
1、必须以post方式提交
2、enctype必须为“multipart/form-data”
3、必须有type=“file”的输入域

struts2进行文件上传有如下注意事项:
1、把在表单中定义的上传文件域的名字,在相应的action类中,定义成File类型,这样框架可以根据其setter方法进行封装(如同设置属性)
2、通过定义文件名fileName可以得到上传文件的名称,而不用像在JavaWeb中学的那样,要切割名字。
3、通过文件名ContentType可以获取文件的mime类型,而不是单单靠文件后缀来判断,这个方法不靠谱。

利用struts2进行文件上传有2种方式:
方式一:
1、得到存储文件的真实路径
2、获取输入输出流
3、读写文件的模版
4、关流

    private File file;    private String fileFileName;    private String fileContentType;         try {            String realpath=ServletActionContext.getServletContext().getRealPath("/files");            InputStream in=new FileInputStream(file);            OutputStream out=new FileOutputStream(realpath+"\\"+fileFileName);            int len=-1;            byte[] b=new byte[1024];            while((len=in.read(b))!=-1){                out.write(b,0,len);            }            out.close();            in.close();            return SUCCESS;        } catch (Exception e) {            e.printStackTrace();            return ERROR;        }

方式二:
利用FileUtils,直接把源文件还有存储的文件名传入参数,即可,(其实,fileUtils就是封装了的方法一)

    private File file;    private String fileFileName;    private String fileContentType;         try {            FileUtils.copyFile(file, new File(realpath+"\\"+fileFileName));            return SUCCESS;        } catch (IOException e) {            e.printStackTrace();            return ERROR;        }

进行多文件上传也是差不多的道理,只不过定义的File 还有fileName等属性,都变成了数组,一定要定义好setter方法!!一定要定义好setter方法!!一定要定义好setter方法!!

要读取里面的内容,就要通过数组的遍历来完成。这里最好通过传统的for来循环,因为也要用到数组索引。

    String realpath=ServletActionContext.getServletContext().getRealPath("/files");        try {            if(files!=null && files.length>0){            for(int i=0;i<files.length;i++)                FileUtils.copyFile(files[i], new File(realpath+"\\"+filesFileName[i]));            ActionContext.getContext().put("message", "上传成功!");            }            return SUCCESS;        } catch (IOException e) {            e.printStackTrace();            return ERROR;        }
1 0
原创粉丝点击