• java 文件上传 下载 总结


    首先引入2个jar
    ![](http://images2017.cnblogs.com/blog/1128666/201711/1128666-20171101145630498-2084371020.png)
    
    package uploaddownload;
    
    import java.io.File;
    import java.io.FileInputStream;
    import java.io.FileNotFoundException;
    import java.io.FileOutputStream;
    import java.io.IOException;
    import java.io.InputStream;
    import java.io.OutputStream;
    import java.sql.Savepoint;
    import java.util.List;
    import java.util.UUID;
    
    import javax.servlet.ServletException;
    import javax.servlet.http.HttpServlet;
    import javax.servlet.http.HttpServletRequest;
    import javax.servlet.http.HttpServletResponse;
    
    import org.apache.commons.fileupload.FileItem;
    import org.apache.commons.fileupload.FileUploadBase;
    import org.apache.commons.fileupload.ProgressListener;
    import org.apache.commons.fileupload.disk.DiskFileItemFactory;
    import org.apache.commons.fileupload.servlet.ServletFileUpload;
    /**
     * 
     * @ClassName UploadBoost
     * @Description TODO(这里用一句话描述这个类的作用)
     * @Author pengzh humi
     * @Date 2017年11月1日 上午10:38:36
     */
    public class UploadBoost extends HttpServlet{
    
    	private static final long serialVersionUID = 1L;
    
    	@Override
    	public void init() throws ServletException {
    		System.out.println("UploadBoost init ...");
    	}
    	@Override
    	protected void doGet(HttpServletRequest req, HttpServletResponse resp)
    			throws ServletException, IOException {
    		System.out.println("DO Get method ...");
    		String saveFile = this.getServletContext().getRealPath("/WEB-INF/upload");
    		String tempPath = this.getServletContext().getRealPath("/WEB-INF/temp");
    		File tempFile = new File(tempPath);
    		if(!tempFile.exists()){
    			tempFile.mkdir();
    		}
    		//消息提示
    		String message="";
    		InputStream in =null;
    		FileOutputStream out = null;
    		
    		try {
    			DiskFileItemFactory factory = new DiskFileItemFactory();
    			factory.setSizeThreshold(1024*1024*5);//5k缓存
    			factory.setRepository(tempFile);//临时保存路径
    			ServletFileUpload upload = new ServletFileUpload(factory);//创建文件解析器
    			upload.setProgressListener(new ProgressListener() {//上传进度
    				public void update(long finished, long total, int rate) {
    					// TODO Auto-generated method stub
    					System.out.println("文件上传进度"+finished+"/"+total+"|"+Math.floor((double)(finished*100/total))+"% rate="+rate);
    				}
    			});
    			upload.setHeaderEncoding("utf-8");//解决文件名乱码
    			if(!ServletFileUpload.isMultipartContent(req)){
    				message = "非媒体文件上传";
    				return;
    			}
    			upload.setFileSizeMax(1024*1024*5);//设置单个文件上传最大为5M
    			upload.setSizeMax(1024*1024*10);//设置上传文件总量最大值为5M
    			
    			List<FileItem> fileList = upload.parseRequest(req);
    			for (FileItem item : fileList) {
    				if(item.isFormField()){
    					System.out.println("表单数据:name="+item.getFieldName()+" value="+item.getString("utf-8"));
    				}else{
    					String fileName =item.getName();
    					if(fileName==null||fileName.trim().equals("")){
    						continue;
    					}
    					System.out.println("上传的文件名:"+fileName);
    					fileName = getFileName(fileName.substring(fileName.lastIndexOf("\")+1));//得到唯一文件名
    					String fileExtName=fileName.substring(fileName.lastIndexOf(".")+1);//得到后缀名
    					String dir = getPaht(fileName, saveFile);
    					System.out.println("唯一文件名:"+fileName+"
    文件扩展名"+fileExtName+"
    保存路径名:"+saveFile+"
    哈希路径:"+dir);
    					in = item.getInputStream();
    					out = new FileOutputStream(dir+"\"+fileName);
    					byte[] buff= new byte[1024];//字节流 1k缓冲
    					int length=0;//文件标记位
    					while((length=in.read(buff, 0, length))>0){
    						out.write(buff, 0, length);
    					}
    				message="文件上传成功";
    				}
    			}
    		}catch (FileUploadBase.FileSizeLimitExceededException  e) {
    			System.out.println("上传失败   "+e.getMessage());
    			message="上传失败   "+e.getMessage();
    		}catch (FileUploadBase.SizeLimitExceededException e) {
    			System.out.println("上传失败   "+e.getMessage());
    			message="上传失败   "+e.getMessage();
    		}catch (Exception e) {
    			System.out.println("上传失败   "+e.getMessage());
    			message="上传失败   "+e.getMessage();
    		}finally{
    			//关闭流 并置空 让JVM去回收
    			out.close();out=null;
    			in.close();in=null;
    			//消息提示
    			System.out.println("message="+message);
    			req.setAttribute("message", message);
    			req.getRequestDispatcher("/message.jsp").forward(req, resp);
    		}
    		
    	}
    	
    	@Override
    	protected void doPost(HttpServletRequest req, HttpServletResponse resp)
    			throws ServletException, IOException {
    		System.out.println("Do Post method ...");
    		doGet(req, resp);
    	}
    	/**
    	 * 
    	 * @param name
    	 * @return 唯一文件名
    	 */
    	public String getFileName(String name){
    		return UUID.randomUUID().toString()+"_"+name;
    	}
    	/**
    	 * 
    	 * @param name
    	 * @param path
    	 * @return 得到哈希路径
    	 */
    	public String getPaht(String name,String path){
    		int hashcode = name.hashCode();
    		int dir1 = hashcode&0xf;
    		int dir2 = dir1>>4;
    //		System.out.println("hashcode="+hashcode+"
    dir1="+dir1+"
    dir2="+dir2);
    		String dir = path +"\"+dir1+"\"+dir2;
    		File file = new File(dir);
    		if(!file.exists()){
    			file.mkdirs();
    //			System.out.println("file==="+file+"   "+file.toURI());
    		}
    		return dir;
    	}
    }
    
    ===============================================================
    
    package uploaddownload;
    
    import java.io.File;
    import java.io.FileInputStream;
    import java.io.FileOutputStream;
    import java.io.IOException;
    import java.io.InputStream;
    import java.io.OutputStream;
    import java.net.URLEncoder;
    
    import javax.servlet.ServletException;
    import javax.servlet.http.HttpServlet;
    import javax.servlet.http.HttpServletRequest;
    import javax.servlet.http.HttpServletResponse;
    /**
     * 
     * @ClassName DownLoadServlet
     * @Description 文件下载
     * @Author pengzh humi
     * @Date 2017年11月2日 下午8:10:20
     */
    public class DownLoadServlet extends HttpServlet{
    
    	private static final long serialVersionUID = 1L;
    
    	@Override
    	protected void doGet(HttpServletRequest req, HttpServletResponse resp)
    			throws ServletException, IOException {
    		String realPaht= this.getServletContext().getRealPath("/WEB-INF/upload");
    		String fileName =req.getParameter("filename");
    		String filePath =findFileBySavePath(fileName, realPaht);
    		File file = new File(filePath+"\"+fileName);//得到需要下载的文件
    		System.out.println("文件下载 DownLoadServlet 路径"+filePath+"\"+fileName);
    		if(!file.exists()){
    			req.setAttribute("message", "你要下载的文件已删除");
    			req.getRequestDispatcher("/message.jsp").forward(req, resp);
    			return;
    		}
    		fileName = fileName.substring(fileName.lastIndexOf('_')+1);
    		 //设置响应头,控制浏览器下载该文件
    		resp.setHeader("content-disposition", "attachment;filename=" + URLEncoder.encode(fileName, "UTF-8"));
    		OutputStream out=resp.getOutputStream();
    		FileInputStream in = new FileInputStream(file);
    		int len =0;
    		byte[] buff= new byte[1024];
    		System.out.println("将下载  DownLoadServlet: "+fileName);
    		while((len=in.read(buff))>0){
    			out.write(buff, 0, len);
    		}
    	}
    	
    	@Override
    	protected void doPost(HttpServletRequest req, HttpServletResponse resp)
    			throws ServletException, IOException {
    		doGet(req, resp);
    	}
    	/**
    	 * 
    	 * @param fileName 	文件名
    	 * @param savePath	下载后保存的路径
    	 * @return
    	 */
    	public String findFileBySavePath(String fileName,String savePath){
    		int hashCode = fileName.hashCode();
    		int dir1 = hashCode&0xf;
    		int dir2 = dir1>>4;
    		String dir = savePath+"\"+dir1+"\"+dir2;
    		System.out.println("保存目录处理:dir1="+dir1+"  dir2="+dir2+" dir="+dir);
    		File file = new File(dir);
    		if(!file.exists()){
    			file.mkdirs();
    		}
    		return dir;
    	}
    }
    
    
    
  • 相关阅读:
    qmake杂
    Qt界面风格设置
    qss使用详解
    QT数据库操作
    Qt语言家的简单使用
    c++11之右值引用和std::move
    c++11之类型萃取type_traits
    c++11之std::bind和function
    c++11之lambda
    vue中input输入框无法输入
  • 原文地址:https://www.cnblogs.com/humi/p/7766779.html
Copyright © 2020-2023  润新知