java文件上传方法
来源:互联网 发布:国外开源网站源码 编辑:程序博客网 时间:2024/06/03 15:00
文件上传方法(一次上传一个文件,多个文件的话,请写循环调用)
Upload.uploadFile(theFile, filePath)
说明:
theFile:类型是FormFile
filePath:action中路径获取方法 this.getServlet().getServletContext().getRealPath("/")
调用此方法返回文件上传后的路径名
上传多个文件时,请设置每个文件之间1秒的延迟,否则文件会被覆盖
package common.com;
import java.io.File;
import java.io.FileOutputStream;
import java.io.InputStream;
import java.io.OutputStream;
import java.text.SimpleDateFormat;
import java.util.Date;
import org.apache.commons.lang.RandomStringUtils;
import org.apache.struts.upload.FormFile;
/**
* @author lsc
* 文件上传
*/
public class Upload {
/**
* 文件上传
* @param theFile(FormFile)
* @param filePath(action中路径获取方法:this.getServlet().getServletContext().getRealPath("/") )
* @return
*/
public static String uploadFile(FormFile theFile , String filePath) {
String fileName = theFile.getFileName();//取得上传的Msds文件名
try{
String hardPath = "";
/*
* 取当前系统路径D:/Tomcat5/webapps/coka/ 其中coka 为当前context
*/
//String filePath = this.getServlet().getServletContext().getRealPath("/");
File savePath = new File(filePath + "UploadFiles//");
if (!savePath.exists()) {
savePath.mkdir();
}
if(!"".equals(fileName)){
InputStream stream = theFile.getInputStream();//把文件读入
// 取得一个5位随机字母数字字符串
String randStr = RandomStringUtils.random(5, true, true);
//ByteArrayOutputStream baos = new ByteArrayOutputStream();
/*
* 建立一个上传文件的输出流 如果是linux系统请把UploadFiles后的"//"换成"/"
*/
hardPath = filePath + "UploadFiles//"+ date() + "!@" + randStr+fileName.substring(fileName.indexOf("."));
//msdsHardPath = filePath + "UploadFiles//"+ date() + "!@" + theFile.getFileName();
OutputStream bos = new FileOutputStream(hardPath);
//D:/Tomcat5/webapps/coka/UploadFiles/DSC01508.JPG
//request.setAttribute("fileName",filePath + "/"
//+ theFile.getFileName());
int bytesRead = 0;
byte[] buffer = new byte[8192];
while ((bytesRead = stream.read(buffer, 0, 8192)) != -1)
{
bos.write(buffer, 0, bytesRead);//将文件写入服务器
}
bos.close();
stream.close();
}
return hardPath;
}
catch (Exception e)
{
System.err.print(e);
return "failure";
}
}
/**
* 获取时间
* @return
*/
private static String date(){
Date now=new Date();
SimpleDateFormat df=new SimpleDateFormat("yyyyMMddhhmmss");
return df.format(now);
}
}
- java文件上传方法
- java文件上传方法
- java三种实现文件上传方法
- 文件上传的方法
- 文件上传的方法
- 文件上传方法
- 文件上传 的方法
- .Net上传文件方法
- 上传文件的方法
- 上传大文件方法
- 上传文件的方法
- putty上传文件方法
- Struts2 上传文件方法
- THINKPHP文件上传方法
- 文件上传接收方法
- web上传文件方法
- Laravel 文件上传方法
- java文件上传jsp教程JavaBean实现多文件上传的两种方法
- 懂我,读我
- C#写windows服务实例
- 你跟的上技术吗?
- 用 javascript + actionScript 解决透明的flash在firefox下滚轮失效的问题!
- BGInfo
- java文件上传方法
- [接口介紹]MII接口详解
- 打开天窗:应用大脑科学提升两性之间的职场关系
- 分页存储过程(1)
- Ajax笔记
- QWT在Windows XP及Ubuntu10.04下的安装使用
- ASP.NET在VS2008中如何实现调试!~~~
- 创建表单元素时需注意。
- Java EE和Domino系统间跨域SSO的实现