原理: 使用html 的<input type=”file” name=”xxx”> 标签,提交form 的几个属性必须为: method=post encType=multipart/form-data;
组件:smartUpload或者commons fileupload
smartUpload代码实现
1。文件预览
function showImage(obj)
{
var str=obj.value;
$("#id").html("<img src='+str'/img>");
}
2.无插件实现上传
//从request中获取文件上传流信息
InputStream file=request.getInputStream();
//把流信息写入磁盘文件
String str="G:/";
File temp=new File("str");//写入文件
//获得输出流
FileOutputStream out=new FileOutputStream(temp);
//循环写入
byte[] b=new Byte[1024];
int n;
while((n=file.read(b))!=-1)
{
out.write(b,0,n);
}
file.close();
out.close();
//获取文件名称和内容
RandomAccessFile f=new RandomAccessFile("temp","r");
f.readLine();
String string=f.readLine();
int beginIndex=string.lastIndexOf("\")+1;
int lastIndex=string.lastIndexOf("\");
String name=string.substr(beginIndex,lastIndex);
getServletContext.getRealPath("/");//getServletContext().getRealPath("/")获取项目路径
文件下载
//定义保存路径
String f=getServletContext().getRealPath("/")+"images/";
String filename=request.getParamter("filename");
response.setContentType("appliaction/x-msdownload");//application/octet-stream;
response.setHeader("Context-Dispoinition","attachment:filename=\"+filename+"\"");
/*
- 解决各浏览器的中文乱码问题
*/
String userAgent = request.getHeader("User-Agent");
String userAgent = request.getHeader("User-Agent");
byte[] bytes = userAgent.contains("MSIE") ? fileName.getBytes()
: fileName.getBytes("UTF-8"); // fileName.getBytes("UTF-8")处理safari的乱码问题
fileName = new String(bytes, "ISO-8859-1"); // 各浏览器基本都支持ISO编码
response.setHeader("Content-disposition",
String.format("attachment; filename=\"%s\"", fileName));
response.setHeader("Content-Length", String.valueOf(fileLength));
byte[] buff = new byte[2048];
int bytesRead;
while (-1 != (bytesRead = bis.read(buff, 0, buff.length))) {
bos.write(buff, 0, bytesRead);
}
bis.close();
bos.close();
}