首页 > 代码库 > 文件上传和下载

文件上传和下载

文件上传:

  前端代码就是和html标签<input type="file" id="fileinput"/>

  后台代码:

public void fileUpload(HttpServletRequest request,HttpServletResponse response) throws IOException {
System.out.println("开始");
 //获取上传路径 字符串拼接 String.format效率好些 一般就是直接+ 或是使用StringBuilderStringBuffer
String p= String.format("%s\\upload\\", request.getSession().getServletContext().getRealPath(File.separator));
if(p.indexOf("ROOT"+File.separator)>0||p.indexOf("root"+File.separator)>0){
p = p.replace("ROOT"+File.separator,"");
}
response.addHeader("x-frame-options","DENY");
response.addHeader("x-frame-options","SAMEORIGIN");
Long returnl = null;
if (request instanceof MultipartHttpServletRequest) {
//获取 InputStream
MultipartHttpServletRequest mr = (MultipartHttpServletRequest) request;
Iterator iter = mr.getFileMap().values().iterator();
if (iter.hasNext()) {
MultipartFile file = (MultipartFile) iter.next();
//获取文件名
String oname = file.getOriginalFilename().replace(File.separator,"");
//文件保存路劲
String uploadRootPath =p;
//保存的文件绝对路径
String uploadName =uploadRootPath +System.currentTimeMillis()+oname;
//判断这个文件夹是否存在,如果不存在则创建
File files = new File(uploadRootPath);
if(!files.exists()){
files.mkdir();
}
//文件放入到InputStream里面去,然后用OutputStream写入到文件
InputStream is = file.getInputStream();
OutputStream os = null;
try{
os = new BufferedOutputStream(
new FileOutputStream(uploadName));
byte[] buffer = new byte[1024*1024];
int bytelen = 0;
while((bytelen = is.read(buffer))>0){
os.write(buffer, 0, bytelen);
}
}finally{
if(is!=null)is.close();
if(os!=null)os.close();
}
}
}
}

文件下载:
前端代码:使用的a标签href的属性请求后台或是使用js写window.location.href=""请求后路径,至于保存的路径就交于浏览器的弹出提 (注意理解
后台代码:
private static void downFileLoad(HttpServletRequest request,
HttpServletResponse response, String fileName, String filePath
) throws Exception {
File file = new File(filePath);// path是源文件的路径
String filename =fileName;// 源文件的名称
InputStream fis = new BufferedInputStream(new FileInputStream(filePath));
byte[] buffer = new byte[fis.available()];
fis.read(buffer);
fis.close();
response.reset();
// 先去掉文件名称中的空格,然后转换编码格式为utf-8,保证不出现乱码,这个文件名称用于浏览器的下载框中自动显示的文件名
response.addHeader("Content-Disposition", "attachment;filename=" + new String(filename.replaceAll(" ", "").getBytes("utf-8"),"iso8859-1"));
response.addHeader("Content-Length", "" + file.length());
OutputStream os = new BufferedOutputStream(response.getOutputStream());
response.setContentType("application/octet-stream");
os.write(buffer);// 输出文件
os.flush();
os.close();
}


文件上传和下载