package com.mandi.servlet.file.impl; import java.io.BufferedInputStream; import java.io.File; import java.io.FileInputStream; import java.io.IOException; import java.io.OutputStream; import java.net.URLEncoder; import java.nio.file.Files; import java.nio.file.Path; import java.nio.file.Paths; import java.util.ArrayList; import java.util.HashMap; import java.util.Iterator; import java.util.List; import java.util.Map; import java.util.Map.Entry; import java.util.UUID; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse; import org.apache.commons.fileupload.FileItem; import org.apache.commons.fileupload.disk.DiskFileItemFactory; import org.apache.commons.fileupload.servlet.ServletFileUpload; import org.apache.log4j.Logger; import org.springframework.stereotype.Service; import org.springframework.web.multipart.MultipartFile; import org.springframework.web.multipart.MultipartHttpServletRequest; import com.mandi.servlet.file.FileLoad; @Service public class FileLoadImpl implements FileLoad{ private Logger log=Logger.getLogger(FileLoadImpl.class); @SuppressWarnings("unchecked") @Override public String uploadFile(String dest/*相对位置*/, HttpServletRequest request,boolean randname) { String directory=""; String filenames="";// if(dest==null) directory=request.getSession().getServletContext().getRealPath(""); else directory=request.getSession().getServletContext().getRealPath(dest); File file=new File(directory); if(!file.exists()) { file.mkdirs(); } DiskFileItemFactory dfif=new DiskFileItemFactory(); ServletFileUpload sf=new ServletFileUpload(dfif); sf.setHeaderEncoding("utf-8"); List list=null; try{ list=sf.parseRequest(request); Iterator it=list.iterator(); while(it.hasNext()) { FileItem fi=it.next(); if(fi.isFormField()) continue; String name1=fi.getName(); if(randname==true) { int point=name1.lastIndexOf("."); if(point>0 && name1.length()>(point+1)) { name1=name1.substring(point); } name1=UUID.randomUUID()+name1; } String filename="";//file.getPath(); if(directory.endsWith(File.separator)) filename=directory+name1; else filename=directory+File.separator+name1; File file1=new File(filename); fi.write(file1); filenames=dest.endsWith(File.separator)?(dest+name1):(dest+"/"+name1);//file relative path filenames=request.getServletContext().getContextPath()+filenames; } }catch (Exception e) { log.error("uploadFile error"); } return filenames; } /** * * @return * @author mengly * @version 创建时间:2016年8月6日 下午5:42:49 */ public Map uploadFileRP(String dir,MultipartHttpServletRequest request,boolean randname){ if(dir==null) dir=request.getSession().getServletContext().getRealPath(""); Path p=Paths.get(dir); if(!Files.exists(p)) try { Files.createDirectories(p); } catch (IOException e) { e.printStackTrace(); return null; } if(!dir.endsWith(File.separator)) dir+=File.separator; Map mpfs=request.getFileMap(); for (Entry en : mpfs.entrySet()) { MultipartFile mf=en.getValue(); if(mf.isEmpty()) continue; Map mp=new HashMap(); String uuid=UUID.randomUUID().toString(); mp.put("name", mf.getOriginalFilename()); mp.put("size", mf.getSize()); mp.put("uuid", uuid); String fullp=dir+uuid+mf.getOriginalFilename(); Path pf=Paths.get(fullp); try { Files.copy(mf.getInputStream(), pf); mp.put("url", fullp); return mp; } catch (IOException e) { e.printStackTrace(); } } return null; } @SuppressWarnings("unchecked") @Override public List uploadFile_map(String dest,HttpServletRequest request,boolean randname){ List list1=new ArrayList(); String directory=""; String filenames="";// if(dest==null) directory=request.getSession().getServletContext().getRealPath(""); else directory=request.getSession().getServletContext().getRealPath(dest); File file=new File(directory); if(!file.exists()) { file.mkdirs(); } DiskFileItemFactory dfif=new DiskFileItemFactory(); ServletFileUpload sf=new ServletFileUpload(dfif); sf.setHeaderEncoding("utf-8"); List list=null; try{ list=sf.parseRequest(request); Iterator it=list.iterator(); while(it.hasNext()) { Map mp=new HashMap(); FileItem fi=it.next(); mp.put("name", fi.getName()); mp.put("size", fi.getSize()); if(fi.isFormField()) continue; String name1=fi.getName(); if(randname==true) { int point=name1.lastIndexOf("."); if(point>0 && name1.length()>(point+1)) { name1=name1.substring(point); } name1=UUID.randomUUID()+name1; } String filename="";//file.getPath(); if(directory.endsWith(File.separator)) filename=directory+name1; else filename=directory+File.separator+name1; File file1=new File(filename); fi.write(file1); filenames=dest.endsWith(File.separator)?(dest+name1):(dest+"/"+name1);//file relative path mp.put("url", filenames); list1.add(mp); } }catch (Exception e) { log.error("uploadFile error"); } return list1; } @SuppressWarnings("unchecked") @Override public List uploadFile_map(String dest,HttpServletRequest request,boolean randname,long size){ List list1=new ArrayList(); String directory=""; String filenames="";// if(dest==null) directory=request.getSession().getServletContext().getRealPath(""); else directory=request.getSession().getServletContext().getRealPath(dest); File file=new File(directory); if(!file.exists()) { file.mkdirs(); } DiskFileItemFactory dfif=new DiskFileItemFactory(); ServletFileUpload sf=new ServletFileUpload(dfif); sf.setHeaderEncoding("utf-8"); List list=null; try{ list=sf.parseRequest(request); Iterator it=list.iterator(); while(it.hasNext()) { Map mp=new HashMap(); FileItem fi=it.next(); mp.put("name", fi.getName()); mp.put("size", fi.getSize()); if(fi.isFormField()) { continue; } if(size!=0) { if(fi.getSize()>size) { log.info("file size 超过限制值!!"); continue; } } String name1=fi.getName(); if(randname==true) { int point=name1.lastIndexOf("."); if(point>0 && name1.length()>(point+1)) { name1=name1.substring(point); } name1=UUID.randomUUID()+name1; } String filename="";//file.getPath(); if(directory.endsWith(File.separator)) filename=directory+name1; else filename=directory+File.separator+name1; File file1=new File(filename); fi.write(file1); filenames=dest.endsWith(File.separator)?(dest+name1):(dest+"/"+name1);//file relative path mp.put("url", filenames); list1.add(mp); } }catch (Exception e) { log.error("uploadFile error"); } return list1; } @Override public Map uploadFile_map(String dest,HttpServletRequest request,FileItem fi,boolean randname,long size){ if(fi==null) return null; String directory=""; String filenames="";// if(dest==null) directory=request.getSession().getServletContext().getRealPath(""); else directory=request.getSession().getServletContext().getRealPath(dest); File file=new File(directory); if(!file.exists()) { file.mkdirs(); } Map mp=new HashMap(); try{ mp.put("name", fi.getName()); mp.put("size", fi.getSize()); if(fi.isFormField()) { return null; } if(size!=0) { if(fi.getSize()>size) { log.info("file size 超过限制值!!"); return null; } } String name1=fi.getName(); if(randname==true) { int point=name1.lastIndexOf("."); if(point>0 && name1.length()>(point+1)) { name1=name1.substring(point); } name1=UUID.randomUUID()+name1; } String filename="";//file.getPath(); if(directory.endsWith(File.separator)) filename=directory+name1; else filename=directory+File.separator+name1; File file1=new File(filename); fi.write(file1); filenames=dest.endsWith(File.separator)?(dest+name1):(dest+"/"+name1);//file relative path mp.put("url", filenames); }catch (Exception e) { log.error("uploadFile error"); } return mp; } @Override public void downloadFile(String displayname, String source, HttpServletResponse response) { if(source==null) return; File file=new File(source); if(!file.exists()) return; response.setContentType("application/x-download"); if(displayname==null) displayname=file.getName(); try{ displayname=URLEncoder.encode(displayname,"utf-8"); response.setHeader("Content-Disposition", "attachment; filename=\""+displayname+"\""); FileInputStream fis=new FileInputStream(file); BufferedInputStream bis=new BufferedInputStream(fis); OutputStream out1=response.getOutputStream(); byte[] bytes=new byte[1024*4]; int length=-1; while((length=bis.read(bytes))!=-1) { out1.write(bytes, 0, length); } out1.flush(); bis.close(); fis.close(); out1.close(); }catch (Exception e) { log.error("downloadFile error"); } file.delete(); } @Override public void downloadFile(String desplayname, String source, HttpServletResponse response, HttpServletRequest request) { File file=new File(source); if(!file.exists()) return; long range=0; if(request.getHeader("Range")!=null) { response . setStatus ( javax . servlet . http . HttpServletResponse . SC_PARTIAL_CONTENT ) ; range=Long . parseLong ( request . getHeader ( "Range" ) . replaceAll ( "bytes=" , "" ) . replaceAll ( "-" , "" ) ) ; } response . setHeader ( "Content-Length" , new Long ( file.length() - range ) . toString ( ) ) ; if(range!=0) { response.setHeader( "Content-Range", "bytes " + new Long(range).toString()+ "-"+new Long(file.length()-1).toString()+"/"+new Long(file.length()).toString()); } response.setContentType("application/x-download"); response.setContentType ( "application/octet-stream"); try { String fn=URLEncoder.encode(desplayname,"utf-8"); response . setHeader ( "Content-Disposition","attachment;filename=\""+fn+"\""); FileInputStream fis=new FileInputStream(file); BufferedInputStream bis=new BufferedInputStream(fis); bis.skip(range); OutputStream out1=response.getOutputStream(); byte[] bytes=new byte[1024*4]; int length=-1; while((length=bis.read(bytes))!=-1) { out1.write(bytes, 0, length); } out1.flush(); bis.close(); fis.close(); } catch (Exception e) { log.error("downloadFile error"+e.getMessage()); }finally{ } } @Override public String realpath2path(String localpath, HttpServletRequest request) { String realpath=request.getServletContext().getRealPath(""); if(localpath==null) return "/"; if(localpath.lastIndexOf(realpath)!=0) return "/"; realpath=localpath.substring(realpath.length()); if(realpath.length()>0 && !realpath.startsWith(File.separator)&&!realpath.startsWith("/")) { realpath="/"+realpath; } realpath=realpath.replaceAll("\\\\", "/"); return realpath; } }