struts文件上传与下载

来源:互联网 发布:手机html软件 编辑:程序博客网 时间:2024/05/16 18:59

今天用struts编写了一个留言板测试程序,其中遇到了一些问题,有些我已经解决了,专门写篇博客记录一下,同时也希望路过的大牛能帮我指点一下我没解决的问题。

问题一:在表单中如果包含file控件,要在form表单中添加enctype="multipart/form-data"属性,否则就会报错argument type mismatch.....

问题二:在使用DispatchAction时,始终不能调用到自己指定的函数方法。解决方法:将原来的execute(...)方法删掉,或者将execute()方法名改掉。

问题三:在上传文件时,有时没有附件上传,但在action不知如何判断是否有附件上传。解决方法:将上传文件部分使用try...catch()...包住,当没有文件上传时,就会发生没有发现文件的异常,此时在catch()块中将message对象的附件属性置为null。

try{//上传文件ms.setAnnex(file.getFileName());String path=this.getServlet().getServletContext().getRealPath("/file")+"\\"+file.getFileName();OperationFile of = new OperationFile();of.upFile(file, path);}catch(Exception e){ms.setAnnex(null);e.printStackTrace();}
问题四:文件下载时,中文的文件名会出现乱码。解决方法:对文件名进行URL编码,fileName = java.net.URLEncoder.encode(fileName,"utf-8");

问题五:当文件下载完成后,会报出 getOutputStream() has already been called for this response这个错误,我把会出现这个问题的地方都检查了一遍,该关闭的流都及时关闭了,实在不知哪一块出现问题,虽然不影响功能,但还是让人不爽。此问题本人实在不能解决,望大神指点。

贴出我的上传和下载的方法,如有不足,还望大家指出:

package com.hefan.utils;import java.io.FileInputStream;import java.io.FileOutputStream;import java.io.IOException;import java.io.InputStream;import java.io.OutputStream;import javax.servlet.http.HttpServletResponse;import org.apache.struts.upload.FormFile;public class OperationFile {public void upFile(FormFile file,String path){InputStream is = null;OutputStream os = null;byte[] buff = new byte[1024];int len = 0;try {is = file.getInputStream();os = new FileOutputStream(path);while((len=is.read(buff))>0){os.write(buff, 0, len);}} catch (Exception e) {// TODO Auto-generated catch blocke.printStackTrace();}finally{try {os.close();is.close();} catch (IOException e) {// TODO Auto-generated catch blocke.printStackTrace();}}}public void downFile(String path,HttpServletResponse response){FileInputStream fis = null;OutputStream os = null;try {fis = new FileInputStream(path);os = response.getOutputStream();byte[] buff = new byte[1024];int len = 0;while((len=fis.read(buff))>0){os.write(buff, 0, len);}} catch (Exception e) {// TODO Auto-generated catch blocke.printStackTrace();}finally{try {os.close();fis.close();} catch (IOException e) {// TODO Auto-generated catch blocke.printStackTrace();}}}}
补充:当你上传的文件名相同时,就会发生文件覆盖,如果你不想文件被覆盖,就需要修改文件名。本人写了一个工具类来产生新的文件名:

import java.util.UUID;public class Mytools {public static String NewFileName(String name){int beginIndex = name.lastIndexOf(".");int endIndex = name.length();//截取文件后缀String suffix = name.substring(beginIndex, endIndex);return UUID.randomUUID().toString()+suffix;}}
通过该方法获得的新文件名是一个16位长的数字,这样文件名相同的概率就很小了。



0 0
原创粉丝点击