文件的上传和下载在web开发中经常被用到,我以前写过几次,但是现在来写还是需要查资料,所以我这次就写在这里,下次要用的时候直接用就可以了。
下面附上的代码都是经过测试的...
public class AttachmentAction {
@Inject("refer:attachmentService")
private AttachmentService service;
/**
* 附件上传
* @param workFlowId 工作流Id
* @param file 上传文件
* @param request
* @return msg
*/
@At("/upload")
@Ok("jsp:/index.jsp")
@Fail("")
@AdaptBy(args={"ioc:myUpload"},type=UploadAdaptor.class)
public AjaxMsgEntity upload(long workFlowId,@Param("file")TempFile tf,HttpServletRequest request){
String fileName=tf.getFile().getName();//获取上传文件名
long size=tf.getFile().length();//获取上传文件的大小
String ext=fileName.substring(fileName.lastIndexOf("."),fileName.length());//获取上传文件的后缀名
AjaxMsgEntity msg=new AjaxMsgEntity();
Attachment attachment=new Attachment();
String path=request.getSession().getServletContext().getRealPath("/uploadTemp");//获取项目相对路径
Date date=new Date();
SimpleDateFormat formatdir=new SimpleDateFormat("yyyyMMdd");//上传文件时根据日期格式化上传文件夹
SimpleDateFormat formatfile=new SimpleDateFormat("yyyyMMddHHmmss");//上传文件时根据日期格式格式化上传文件
String dirPath=path+"/"+formatdir.format(date);//文件夹路径
String random=getRandomString();//随机字符串
String filePath=dirPath+"/"+formatfile.format(date)+random+ext;//上传文件路径
String savePath="/uploadTemp/"+formatdir.format(date)+"/"+formatfile.format(date)+random+ext;//数据库保存路径
/**
* 判断以日期为名的文件夹是否存在
*/
File dir=new File(dirPath);
if(dir.exists()&&dir.isDirectory()){
}else{
dir.mkdir();
}
try {
//创建文件输入流
BufferedInputStream is=new BufferedInputStream(new FileInputStream(tf.getFile()));
//创建文件输出流
FileOutputStream out=new FileOutputStream(filePath);
byte buffer[]=new byte[1024];//创建一个文件缓冲区
int len =0;//判断输入流中的数据是否已经读完的标识
/**
* 循环读出数据
*/
while((len=is.read(buffer))>0){
out.write(buffer, 0, len);
}
is.close();//关闭输入流
out.close();//关闭输出流
attachment.setAttachmentDate(date);
attachment.setAttachmentName(fileName);
attachment.setAttachmentPath(savePath);
attachment.setAttachmentSize(size);
boolean flag=service.saveOrUpdate(attachment);
if(flag){
msg.setMsg("上传成功!");
msg.setStatus(true);
}else{
System.out.println("数据库添加失败...");
msg.setMsg("上传失败!");
msg.setStatus(false);
}
} catch (FileNotFoundException e) {
// TODO Auto-generated catch block
e.printStackTrace();
System.out.println("没有找到上传文件,上传失败...");
msg.setMsg("上传失败!");
msg.setStatus(false);
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
System.out.println("文件流读取失败,上传失败...");
msg.setMsg("上传失败!");
msg.setStatus(false);
}
return msg;
}
/**
* 附件下载
* @param request
* @param response
* @param fileName
*/
@At("/download")
@Ok("void")
public void download(HttpServletRequest request,HttpServletResponse response,String fileName){
//String fileName ="试题.xls";
String root=this.getClass().getResource("/").getFile();
String path=root.substring(1,root.indexOf("WEB-INF"));
try {
response.setHeader("Content-disposition","attachment; filename="+new String
(fileName.getBytes("UTF-8"),"iso-8859-1"));
} catch (UnsupportedEncodingException e2) {
// TODO Auto-generated catch block
e2.printStackTrace();
}
response.setContentType("application/octet-stream");
BufferedInputStream bis = null;
BufferedOutputStream bos = null;
//ServletOutputStream bos=null;
try {
bis = new BufferedInputStream(new FileInputStream(path+fileName));
bos = new BufferedOutputStream(response.getOutputStream());
// bos=response.getOutputStream();
byte[] buff = new byte[2048];
int bytesRead;
while(-1 != (bytesRead = bis.read(buff, 0, buff.length))) {
bos.write(buff,0,bytesRead);
}
bos.flush();
} catch(final IOException e) {
System.out.println ( "IOException." + e );
} finally {
if (bis != null)
try {
bis.close();
} catch (IOException e1) {
// TODO Auto-generated catch block
e1.printStackTrace();
}
if (bos != null)
try {
bos.close();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
}
/**
* 随机生成4位数的字符串
* @return
*/
public String getRandomString(){
StringBuffer str= new StringBuffer();
Random random=new Random();
for(int i=0;i<4;i++){
str.append(String.valueOf(random.nextInt(10)));
}
return str.toString();
}
}