action中的代码
try {
// 多附件上传
MultipartRequestHandler mrh = conForm.getMultipartRequestHandler();
Map formFiles = mrh.getFileElements();
String fileName="";
if (formFiles!=null){
AnnexsUpload au = new AnnexsUpload(req,res);//获得上传附件通用对象
Iterator it = formFiles.values().iterator();
while (it.hasNext()) {
//图片上传
FormFile file = (FormFile)it.next();
au.setSaveDir(this.servlet.getServletContext().getRealPath("/loadImage/"));//将图片放入存储文件路径
fileName=au.randomFileName(file.getFileName());
au.upload(au.getSaveDir()+File.separator+ fileName, fileName, file);//上传附件
//保存记录
IAttachmentDAO ia = new AttachmentDAO();
TabAttachment att = new TabAttachment();
att.setFieldId(con.getCoid());//把资讯表的id添加到附件表里面
att.setTableName(tableName); //关联的表名
att.setAttachFile(fileName); //上传到服务器的文件名
att.setRemark(file.getFileName());//文件原来的真名
att.setUploadName(user.getRealname()); //上传者,即登录者姓名
ia.addAttachment(att);
}
}
} catch (Exception e) {
}
AnnexsUpload.java
package com.bcc.comm;
import java.io.BufferedInputStream;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.OutputStream;
import java.io.UnsupportedEncodingException;
import java.net.MalformedURLException;
import java.net.URL;
import java.util.List;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import org.apache.commons.fileupload.DiskFileUpload;
import org.apache.commons.fileupload.FileItem;
import org.apache.commons.fileupload.FileUploadException;
import org.apache.struts.upload.FormFile;
public class AnnexsUpload {
private HttpServletResponse response;
private HttpServletRequest request;
private String saveDir;//文件保存路径
private String oldFileName;//原始文件名
private String newFileName;//新文件名
private String newFilePath;//新文件路径
private long fileSize;//文件大小
private long maxFileSize = 1024 * 1024 * 20;//上传文件最大大小6M
private int thresholdSize = 4000;//起始大小
public AnnexsUpload(HttpServletRequest request, HttpServletResponse response) {
super();
this.response = response;
this.request = request;
}
//产生随机文件名
public synchronized String randomFileName(String fileName){
String temp = fileName.substring(fileName.lastIndexOf("."));//得到文件扩展名
try {
Thread.sleep(10);//如果有多个线程同时上传就休眠1毫秒,这样就可以避免产生的文件名一样
} catch (InterruptedException e) {
e.printStackTrace();
}
return System.currentTimeMillis() + temp;
}
//文件目录不存在则创建
public void setSaveDir(String saveDir){
this.saveDir = saveDir;
File f = new File(this.saveDir);
if(!(f.isDirectory())){
f.mkdirs();
}
}
//上传单个文件
public boolean upload(){
DiskFileUpload dfu = new DiskFileUpload();
dfu.setSizeMax(this.maxFileSize);//设置上传文件最大值
dfu.setSizeThreshold(this.thresholdSize);//设置初始大小
dfu.setRepositoryPath(this.newFilePath);//设置上传路径
List list = null;
try {
list = dfu.parseRequest(this.request);//解析request并且返回list集合
} catch (FileUploadException e) {
e.printStackTrace();
}
// System.out.println(list.isEmpty());
for (int i = 0; i < list.size(); i++) {
FileItem fi = (FileItem) list.get(i);
try {
//中文编码转换
this.oldFileName = new String(fi.getFieldName().getBytes(),"GB2312");
//得到原始文件名
this.oldFileName = this.oldFileName.substring(this.oldFileName.indexOf("//") + 1);
this.fileSize = fi.getSize();
if(this.fileSize > this.maxFileSize){
System.out.println("文件太大");
return false;
}
this.newFileName = this.randomFileName(this.oldFileName);
this.newFilePath = this.saveDir + this.newFileName;
File f = new File(this.saveDir,this.newFileName);
fi.write(f);
} catch (UnsupportedEncodingException e) {
e.printStackTrace();
return false;
} catch (Exception e) {
e.printStackTrace();
return false;
}
}
return true;
}
//上传新文件
/* public boolean upload(FormFile file){
try {
this.fileSize = file.getFileSize();
if(this.fileSize > this.maxFileSize){
System.out.println("文件太大");
return false;
}
this.oldFileName = new String(file.getFileName().getBytes(),"GB2312");
this.oldFileName = this.oldFileName.substring(this.oldFileName.lastIndexOf("//") + 1);
this.newFilePath = this.saveDir + "//" + this.randomFileName(this.oldFileName);
this.newFileName = this.randomFileName(this.oldFileName);
AnnexsBean fb = new AnnexsBean();
fb.AddAnnexs(new Annexs(this.newFilePath,this.newFileName,this.fileSize + ""));
//构造输入流
BufferedInputStream bis = new BufferedInputStream(file.getInputStream(),(int)this.fileSize);
File f = new File(this.newFilePath);
FileOutputStream fos = new FileOutputStream(f);
byte[] b = new byte[1024];
int len = 0;
while((len = bis.read(b)) > 0){
fos.write(b,0,len);//从缓冲区里读取数据写入输出流
}
fos.close();
bis.close();
return true;
} catch (Exception e) {
e.printStackTrace();
return false;
}
}*/
//以自定义的名称保存文件
public boolean upload(String filePath,String fileName,FormFile file){
this.fileSize = file.getFileSize();
if(this.fileSize > this.maxFileSize){
System.out.println("文件太大");//如果大于6M
return false;
}
this.oldFileName = file.getFileName();
this.newFileName = fileName;
this.newFilePath = filePath;
try {
BufferedInputStream bis = new BufferedInputStream(file.getInputStream(),(int)this.fileSize);
File f = new File(this.newFilePath);
FileOutputStream fos = new FileOutputStream(f);
byte[] b = new byte[1024];
int len = 0;
while((len = bis.read(b)) > 0){
fos.write(b,0,len);
}
fos.close();
bis.close();
return true;
} catch (FileNotFoundException e) {
e.printStackTrace();
return false;
} catch (IOException e) {
e.printStackTrace();
return false;
}
}
//删除文件
public static boolean deleteFile(String path){
File f = new File(path);
if(f.exists()){
f.delete();
return true;
}else
return false;
}
/**
* 删除文件
* @param uploadPath 文件的路径
* @param fileName 文件名
*/
public static void deleteFile(String uploadPath,String fileName){
File file = new File(uploadPath+fileName);
if(file.exists()){
file.delete();
}else{
// System.out.println(uploadPath+fileName+"文件不存在");
}
}
public void setSaveDirReport(String saveDir){
this.saveDir = saveDir;
File f = new File(this.saveDir);
if(f.isDirectory()){
f.mkdirs();
}
}
//文件下载
public void download(String filePath,String fileName,boolean isOnline){
File file = new File(filePath);
System.out.println(filePath);
if(!file.exists()){
try {
throw new Exception("文件不存在");
} catch (Exception e) {
e.printStackTrace();
}
return;
}
try {
BufferedInputStream bis = new BufferedInputStream(new FileInputStream(file));
byte[] b = new byte[1024];
int len = 0;
response.reset();
if(isOnline){
URL url = new URL("file:///" + filePath);
response.setContentType(url.openConnection().getContentType());
response.setHeader("Content-Disposition", "inline;filename=" + new String((fileName + filePath.substring(filePath.lastIndexOf("."))).getBytes(),"ISO-8859-1"));
}else{
response.setContentType("application/x-msdownload");
response.setHeader("Content-Disposition", "attachment; filename=" + new String((fileName+filePath.substring(filePath.lastIndexOf("."))).getBytes(),"ISO-8859-1"));
}
OutputStream out = response.getOutputStream();
while((len = bis.read(b)) > 0){
out.write(b,0,len);
}
out.close();
bis.close();
} catch (FileNotFoundException e) {
e.printStackTrace();
} catch (MalformedURLException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
}
}
jsp页面代码
<tr>
<th>附件</th>
<td colspan="3" >
<input type="checkbox" id="chkAtt" οnclick="myShow();">上传附件
<table>
<c:forEach var="listatt" items="${listAtt}">
<tr id="imgdiv${listatt.tatId}"><td style="border:0px;">${listatt.remark}
<a href="javascript:form111(${listatt.tatId})"><img border="0" alt="删除" src="<%=request.getContextPath()%>/background/images/del.jpg"/></a>
</td>
</tr>
<tr><td><div id="mdiv"></div></td></tr>
</c:forEach>
</table>
<table width="100%" style="display: none;" id="PLList" class="chart_list">
<tr><td align="left" width="38%">
<input type="file" name="file" size="49" class="inputs" />
<td>
<nobr>
<input type="button" value=" + " οnclick="insertRow()" class="buttoncss" title="增加一行">
<input type="button" onClick="DeleteRow('PLList')" value=" - " class="buttoncss" title="删除一行">
</nobr>
<input type="hidden" value="0" name="count" id="count">
<input type="hidden" name="isInputmavin" id="isInputmavin" value="0">
<input type="hidden" name="orderNo" id="orderNo">
</td></tr>
</table>
</td>
</tr>
function form111(pid){
var imgdiv = $("#imgdiv"+pid);
var mdiv = $("#mdiv");
$.post('contentManage.do?method=deleteFileUp&tatid='+pid,null,function callback1(data){});
imgdiv.hide();
//mdiv.text("删除成功!").css("color","red");
}
down.jsp下载页面
<%@ page language="java" pageEncoding="UTF-8"%>
<%@ page import="com.jspsmart.upload.SmartUpload"%>
<%
//下载文件页面
SmartUpload down = new SmartUpload();
//初始化环境
down.initialize(pageContext);
//得到下载文件参数名称
String file =(String)request.getParameter("file");
//重新设置字符编码 如果有必要
//file = new String(file.getBytes("ISO8859_1-1"),"GBK");
try{
down.setContentDisposition(null);
String descFileName = file;
byte[] b = descFileName.getBytes();
char[] c = new char[b.length];
for (int x = 0; x < b.length; x++)c[x] = (char) (b[x] & 0x00FF);
descFileName = new String(c);
down.downloadFile(file,"text/xml/txt",descFileName);
out.clear();
out = pageContext.pushBody();
}catch(Exception ex){
System.out.println("下载文件失败!<br>");
out.println("下载文件失败!<br>");
out.println("错误原因:<br>"+ex.toString());
}
%>
---
<a href="<%=request.getContextPath()%>/background/contentManage/view/down.jsp?file=${hurl}${listatt.attachFile}">下载</a></td>
=========
懒得敲代码。写的拿过来放这里。用时。直接用。