文件上传:部分代码
String jywm=file[i].substring(file[i].lastIndexOf("//")+1);
String prefix= getServletContext().getRealPath(Global.DEFAULT_UPLOADFILE_PATH+"//");
// 判断路径是否存在,不存在则生成目录
File tmpfile = new File(prefix);
if(!tmpfile.exists()){
tmpfile.mkdirs();
}
prefix=prefix+"//"+jywm;
try{
FileInputStream in=new FileInputStream(file[i]);
OutputStream bos = new FileOutputStream(prefix);
int bytesRead = 0;
byte[] buffer = new byte[8192];
while ((bytesRead = in.read(buffer, 0, 8192)) != -1) {
bos.write(buffer, 0, bytesRead);
}
bos.close();
in.close();
File file2=new File(prefix); //得到文件大小
long filesize=file2.length();
//写入原文信息到数据库
saveYwxx(ywzid,filesize,jywm,oluser.getUsid(),itcommonYwxxBIZ);
}catch(FileNotFoundException ex1){
request.setAttribute("message","���无法找得要写入文件的位置!");
ex1.printStackTrace();
return mapping.findForward("failure");
}catch(IOException ex2){
request.setAttribute("message","写入原文信息失败");
ex2.printStackTrace();
return mapping.findForward("failure");
}
}
文件下载:
/**
* 文件夹下载
* Action层的下载文件方法必须传 一个文件的完整路径过来
* request.setAttribute("fullFileName",fullFileName)
* @author flx
* @param fullFileName 文件路径
*/
public class Download extends HttpServlet {
protected final Log logger = LogFactory.getLog(getClass());
/**
* Destruction of the servlet. <br>
*/
public void destroy() {
super.destroy();
}
public void doGet(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
BufferedInputStream bis = null;
BufferedOutputStream bos = null;
if(null==request.getAttribute("fullFileName")) return ;
String fullFileName = (String)request.getAttribute("fullFileName");
String wjmc=fullFileName.substring(fullFileName.lastIndexOf("//")+1);
if(logger.isInfoEnabled()){
logger.info( " 下载的文件路径为: " + fullFileName);
}
try {
bis = new BufferedInputStream(new FileInputStream(fullFileName));
bos = new BufferedOutputStream(response.getOutputStream());
response.setContentType("APPLICATION/OCTET-STREAM");
response.setContentLength(bis.available());
response.setHeader("Content-Disposition","attachment; filename=/""+new String(wjmc.getBytes("gbk"),"iso8859-1")+"/"");
byte[] buff = new byte[2048];
int bytesRead;
while(-1 != (bytesRead = bis.read(buff, 0, buff.length))) {
bos.write(buff,0,bytesRead);
}
} catch( IOException e) {
System.out.println("下载文件时发生错误:"+e);
} finally {
if (bis != null)
bis.close();
if (bos != null)
bos.close();
}
return;
}
public void doPost(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
doPost(request,response);
}
public void init() throws ServletException {
}