上传文件

---周攀
JSP或HTML页面代码:
<html>
<head>
<title>上传无限多个文件</title>
<style>
a.addFile{
background-image:url(scfj.gif);
background-repeat:no-repeat;
display:block;
float:left;
height:20px;
margin-top:-1px;
position:relative;
text-decoration:none;
top:0pt;
width:75px;
}
input.addFile{
cursor:pointer !important;
height:20px;
left:-2px;
filter:alpha(opacity=0);
position:absolute;
top:0px;
width:1px;
z-index:-1;
}
</style>
<script type="text/javascript">
var fileCount = 1;
function fileChange(element){
var newElement = document.createElement('input');
newElement.type = "file";
newElement.size = 1;
newElement.title="点击选择附件";
newElement.name = "file" + ++fileCount;
newElement.className = "addFile";
newElement.onchange = function(){
fileChange(this);
};
element.parentNode.insertBefore(newElement, element);
element.style.position = 'absolute';
element.style.left = '-1000px';
var newTag = document.createElement('span');
newTag.innerHTML = " " + getFileName(element.value);
var newImg = document.createElement('img');
newImg.src = "del.gif";
newImg.alt="删除";
newImg.style.cursor="hand";
newImg.οnclick=function(){
delFile(element, this);
}
newImg.border="0";
newImg.align="absmiddle";
newTag.appendChild(newImg);
FileShow.appendChild(newTag);
}
function delFile(eFile,eTag){
eFile.parentNode.removeChild(eFile);
eTag.parentNode.parentNode.removeChild(eTag.parentNode);
}
function getFileName(_path){
var unix = _path.lastIndexOf("/");
var dos = _path.lastIndexOf("\\");
var dos = dos > unix ? dos : unix;
if (dos != -1) {
return _path.substring(dos + 1);
}else{
return _path;
}
}
</script>
</head>
<body>
<form action="这里看上传处理的页面" method="post" enctype="multipart/form-data">
<table><tr><td style="font-size:9pt"><span id="FileShow"></span></td>
<td><a href="#" class="addFile"><input class="addFile" type="file" name="file1" οnchange="fileChange(this)" size="1" title="点击选择附件"></a>
</td></tr></table>
<input type="submit" value="上传" alt="上传" />
</form>
</body>
</html>
上传处理的JAVA类 Upload.java:
import java.io.File;
import java.io.FileOutputStream;
import java.util.ArrayList;
import java.util.Enumeration;
import java.util.Hashtable;
import java.util.Iterator;
import java.util.List;
import javax.servlet.http.HttpServletRequest;
import org.apache.commons.fileupload.DiskFileUpload;
import org.apache.commons.fileupload.FileItem;
import org.apache.struts.action.ActionForm;
import org.apache.struts.upload.FormFile;
public class Upload {
/**
* 通过HttpServletRequest对象上传多个文件
*
* @param req
* @param uploadDir
* @return
*/
@SuppressWarnings("unchecked")
public static List<FileBean> requestUpload(HttpServletRequest req,
String uploadDir) {
if (!(uploadDir.endsWith("/") || uploadDir.endsWith("\\")))
uploadDir += "\\";
File fileDir = new File(uploadDir);
if (!fileDir.exists())
fileDir.mkdirs();
List<FileBean> beans = new ArrayList<FileBean>();
DiskFileUpload fu = new DiskFileUpload();
fu.setSizeMax(2 * 1024 * 1024);// 文件最大大小2M
fu.setRepositoryPath(uploadDir);
fu.setSizeThreshold(10240);
try {
List<FileItem> fileItems = fu.parseRequest(req);
Iterator<FileItem> iter = fileItems.iterator();
while (iter.hasNext()) {
try {
FileItem item = (FileItem) iter.next();
if (!item.isFormField()) {
String realName = removePath(item.getName());
if ((realName == null || realName.equals(""))
&& item.getSize() == 0)
continue;
String localName = System.currentTimeMillis() + ".dat";
String file = uploadDir + localName;
item.write(new File(file));
beans.add(new FileBean(realName, localName));
}
} catch (Exception e) {
System.out.println("上传文件失败:" + e.getMessage());
}
}
} catch (Exception e) {
System.out.println("上传文件失败:" + e.getMessage());
}
return beans;
}
/**
* 通过ActionForm对象上传多个文件
*
* @param form
* @param uploadDir
* @return
*/
@SuppressWarnings("unchecked")
public static List<FileBean> formUpload(ActionForm form, String uploadDir) {
if (!(uploadDir.endsWith("/") || uploadDir.endsWith("\\")))
uploadDir += "\\";
File fileDir = new File(uploadDir);
if (!fileDir.exists())
fileDir.mkdirs();
List<FileBean> beans = new ArrayList<FileBean>();
Hashtable<String, FormFile> fileHash = form
.getMultipartRequestHandler().getFileElements();
for (Enumeration<String> e = fileHash.keys(); e.hasMoreElements();) {
String key = (String) e.nextElement();
try {
FormFile formfile = (FormFile) fileHash.get(key);
String realName = removePath(formfile.getFileName().trim());
if (!"".equals(realName)) {
byte[] data = formfile.getFileData();
String localName = System.currentTimeMillis() + ".dat";
String filePath = uploadDir + localName;
FileOutputStream fileOut = new FileOutputStream(filePath);
fileOut.write(data);
fileOut.close();
beans.add(new FileBean(realName, localName));
}
} catch (Exception ex) {
System.out.println("上传文件失败:" + ex.getMessage());
}
}
return beans;
}
/**
* 从文件地址中取得文件名
*
* @param filePathName
* @return
*/
private static String removePath(String filePathName) {
if (filePathName.endsWith("/") || filePathName.endsWith("\\"))
filePathName.substring(0, filePathName.length());
int unix = filePathName.lastIndexOf("/");
int dos = filePathName.lastIndexOf("\\");
int splite = dos > unix ? dos : unix;
if (splite != -1) {
return filePathName.substring(splite + 1);
} else {
return filePathName;
}
}
}
保存文件信息的JAVA类 FileBean.java:
public class FileBean {
private String realName;//真实文件名
private String localName;//本地保存的文件名
public FileBean() {
}
public FileBean(String realName, String localName) {
this.realName = realName;
this.localName = localName;
}
public String getRealName() {
return realName;
}
public void setRealName(String realName) {
this.realName = realName;
}
public String getLocalName() {
return localName;
}
public void setLocalName(String localName) {
this.localName = localName;
}
}
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值