文件上传下载

来源:互联网 发布:php登陆注册页面模板 编辑:程序博客网 时间:2024/05/22 02:29

Struts2单文件上传

1创建文件file.jsp

<form action="uploadfile"enctype="multipart/form-data" method="post">

     <input type="file"name="myfile"/>

     <input type="submit"value="提交"/>

</form>

2创建action

public class MyFileUpload extends ActionSupport{

private StringmyfileFileName;

private Filemyfile;

private StringmyfileContentType;

public String upload()throws IOException{

//得到上传文件保存的路径

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

//上传后保存的文件

File outFile=new File(savePath+"/"+myfileFileName);

//上传文件操作

FileUtils.copyFile(myfile, outFile);

return "success";

}

//省略get/set方法

}

说明:上面的FileUtils.copyFile(face, outfile);  方法,使用Common-io.jar文件中的一个工具类。如果不使用该方法,可以自己实现文件的读写

FileOutputStream fos = new FileOutputStream("D:/struts/"+myfileFileName);

FileInputStream fis = new FileInputStream(myfile);

byte[] b = new byte[1024];

int len = 0;

while((len = fis.read(b))!=-1){

fos.write(b,0,len);

}

fos.close();

fis.close();

3配置struts.xml文件

<action name="*file"class="base.MyFileUpload" method="{1}">

<result>/success.jsp</result>

</action>

修改文件上传

增加文件类型的过滤,文件大小的过滤

修改action

public class MyFileUpload extends ActionSupport{

private StringmyfileFileName;

private Filemyfile;

private StringmyfileContentType;

private Stringmsg;

private long allowSize;

private StringallowType;

public String upload()throws IOException{

if(myfile!=null){

//判断文件大小

if(isAllowSize()){

//判断文件类型

if(isAllowType()){

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

File outFile=new File(savePath+"/"+myfileFileName);

FileUtils.copyFile(myfile, outFile);

return "success";

}else{

msg="文件类型不符";

return "error";

}

}else{

msg="文件过大";

return "error";

}

}

return "success";

}

//判断大小是否符合要求

public boolean isAllowSize(){

if(myfile!=null){

long size=myfile.length();

System.out.println(size);

if(size>allowSize){

return false;

}else{

return true;

}

}

return false;

}

//判断文件类型是否符合要求

public boolean isAllowType(){

String fileType=myfileFileName.substring(myfileFileName.indexOf(".")+1);

String[] type=allowType.split(",");

for(int i=0;i<type.length;i++){

if(fileType.equals(type[i])){

return true;

}

}

return false;

}

//省略get/set方法

}

修改struts.xml

<action name="*file"class="base.MyFileUpload" method="{1}">

<param name="allowType">jpg,zip,text,gif</param>

<param name="allowSize">1048000</param>

<result name="error">/file.jsp</result>

<result>/success.jsp</result>

</action>

注意:文件上传一定要完成:a、文件类型的过滤;b、文件大小的过滤。在Struts中,可以用struts自带的拦截器来完成。

整个表单的总文件的大小,不能超过struts.properties里限定的大小,如:

struts.multipart.maxSize=10971520

过滤文件的大小,类型如:

<interceptor-ref name="fileUpload">

<param name="maximumSize">4194304</param>

<!-- 配置允许上传文件的类型,如果有多个类型用","隔开 -->  

            <param name="fileUpload.allowedTypes">application/vnd.ms-excel,text/plain</param>  

            <!--配置允许上传文件的扩展名,如果有多个用","隔开  -->  

            <param name="fileUpload.allowedExtensions">txt,excel,ppt</param> 

 

</interceptor-ref>

 

 

 

 

多文件上传

public class MyFileUpload extends ActionSupport{

private String[]myfileFileName;

private File[]myfile;

private String[]myfileContentType;

public String upload()throws IOException{

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

//确保有上传文件

if(myfile!=null&&myfile.length>0){

for(int i=0;i<myfile.length;i++){

File outFile=new File(savePath+"/"+myfileFileName[i]);

if(myfile[i]!=null&&myfile[i].length()>0){

FileUtils.copyFile(myfile[i], outFile);

}else{

System.out.println("上传有误");

}

}

}

return "success";

}

//省略

}

 

 

 

 

 

默认的错误信息

struts2-core-2.x.x.x.jar\org\apache\struts2\struts-messages.properties文件中定义:

struts.messages.error.uploading=Error uploading: {0}

struts.messages.error.file.too.large=File too large: {0} "{1}" "{2}" {3}

struts.messages.error.content.type.not.allowed=Content-Type not allowed: {0} "{1}" "{2}" {3}

struts.messages.error.file.extension.not.allowed=File extension not allowed: {0} "{1}" "{2}" {3}

{0}:<input type=“file” name=“uploadImage”>name属性的值

{1}:上传文件的名称

{2}:上传文件保存到临时目录的名称

{3}:上传文件的类型(struts.messages.error.file.too.large是上传文件的大小)

我们可以在Action的统计目录下创建一个fileuploadmessage.properties文件,文件名没有要求,但必须是properties文件,在其中输入:

struts.messages.error.uploading=上传错误: {0}

struts.messages.error.file.too.large=文件太大: {0} "{1}" "{2}" {3}

struts.messages.error.content.type.not.allowed=不支持的文件类型: {0} "{1}" "{2}" {3}

struts.messages.error.file.extension.not.allowed=不支持的文件扩展名: {0} "{1}" "{2}" {3}

<constant name="struts.custom.i18n.resources" value="cn.xing.upload.fileuploadmessage">

</constant>

 

文件下载

如果是非中文的文件名,可以直接采用超级链接的方式提供下载,如:

<a href="${pageContext.request.contextPath}/download/yinhe.zip">下载yinhe</a>

但是,该中下载方式,不能支持中文文件名和权限认证。

下面使用Struts完成文件下载:

获取下载列表

创建action

public class DownloadAction extends ActionSupport{

private File[]files;

public String list(){

//取得文件保存路径

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

File f=new File(path);

//获取目录下保存的文件

files=f.listFiles();

return "list";

}

//省略get/set

}

配置struts.xml

<action name="*down"class="base.MyFileUpload" method="{1}">

<result name="list">/filelist.jsp</result>

</action>

创建fileslist.jsp

<body>

    <c:forEach items="${files }" var="f">

     ${f.name}<br/>

    </c:forEach>

  </body>

修改action代码

public class DownloadAction extends ActionSupport{

private File[]files;

private StringfileName;

public String list(){

//取得文件保存路径

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

File f=new File(path);

//获取目录下保存的文件

files=f.listFiles();

return "list";

}

public InputStream  getDownloadFile()throws Exception{

String filePath = ServletActionContext.getRequest()

.getServletContext().getRealPath("/upload/"+fileName);

InputStream is =new FileInputStream(new File(filePath));

//解决下载文件名称问题

fileName=URLEncoder.encode(fileName,"UTF-8");

return is;

}

public void setFileName(String fileName)throws UnsupportedEncodingException {

//处理get请求中文乱码

this.fileName =new String(fileName.getBytes("iso8859-1"),"utf-8");

}

public File[] getFiles() {

return files;

}

public void setFiles(File[] files) {

this.files = files;

}

public String getFileName() {

return fileName;

}

}

修改struts.xml文件

<action name="*down"class="base.DownloadAction" method="{1}">

<result name="list">/filelist.jsp</result>

<result type="stream">

<!--下载的文件数据存放的方法,该方法返回一个InputStream

例如取值为inputStream的属性需要编写getInputStream()方法-->

<param name="inputName">downloadFile</param>

<!--下载时,客户端显示的下载的文件名-->

<param name="contentDisposition"> 

attachment; filename=${fileName}

</param>

<!--数据的缓冲大小 -->

<param name="bufferSize">1024</param>

</result>

</action>

attachment;filename="struts2.txt",表示文件下载的时候保存的名字应为struts2.txt

如果直接写filename="struts2.txt",那么默认情况是代表inline,浏览器会尝试自动打开它,等价于这样的写法:inline; filename="struts2.txt" 

contentType 

内容类型,和互联网MIME标准中的规定类型一致,例如text/plain代表纯文本,text/xml表示XMLimage/gif代表GIF图片,image/jpeg代表JPG图片

原创粉丝点击