最简单的上传下载,整理一下,以后用着方便
上传:
前端界面 ( type = "file"是用来选择文件)
<form action="infopbl/DocInfopbl_addTswj" method="post" name="addTswjForm"; οnsubmit="return check2()" enctype="multipart/form-data">
请选择文档:
<input class="xzwd" id="word" name="tswj.wjmc" type="file" value="浏览">
<input type="submit" value="提交">
<input id="reset" type="button" value="重置">
</form>
后台程序处理
File fileIn = new File(saveName); //savename为临时文件路径,是前台选择文件的name值(tswj.wjmc)
String tomcat = ServletActionContext.getServletContext().getRealPath("/upload");
String yafile = tomcat+"\\"+lj;
File fileOut = new File(yafile); //yafile为文件需要上传到的路径
FileInputStream fis = new FileInputStream(fileIn);
FileOutputStream fos = new FileOutputStream(fileOut);
BufferedInputStream bis = new BufferedInputStream(fis);
BufferedOutputStream bos = new BufferedOutputStream(fos);
byte[] b = new byte[(int) fileIn.length()]; //注意此处长度定义,按照文件大小定义,能够好的保证文件完整性
int len = 0;
if((len = bis.read(b)) != -1) {
bos.write(b, 0, len);
}
fis.close();
fos.close();
下载:
String wjmc = tswj.getWjmc();
// String wjmc = "ceshi.xls";
try{
response.setCharacterEncoding("utf-8");
response.setHeader("Content-Disposition", "attachment;filename="
+ new String((wjmc).getBytes(),"ISO-8859-1"));// 设定输出文件头
response.setContentType("multipart/form-data");// 定义输出类型为所有
OutputStream os = response.getOutputStream();
File file = new File(ServletActionContext.getServletContext().getRealPath("/upload")+"\\"+wjmc);
InputStream inputStream = new FileInputStream(file);
//写文件
byte[] b = new byte[(int)file.length()];
int len = 0;
if((len = inputStream.read(b))>0) {
os.write(b,0,len);
}
//关闭输出流
os.close();
inputStream.close();
}catch(Exception e){
e.printStackTrace();
}