JavaWeb后台上传下载文件

有建议请留言,共同探讨。

public class FileUtil {
	//需要保存的目录 格式(/目录名)
	private String path;
	//保存的全路径
	private String savePath;
	//临时文件路径
	private String temPath="/temp";
	//缓冲区大小(b) 默认设置为10M
	private int bufferSize=1024*1024*10;
	//单个文件大小 单位(b) 默认设置为50M
	private long maxSize = (long)(1024*1024*50);
	//同时上传文件大小 单位(b) 默认设置为200M
	private long max = (long)(1024*1024*200);
	//允许上传的文件类型(后缀名) 默认设置为全部可以上传
	private List fileSuffName = null;
	public List getFileSuffName() {
		return fileSuffName;
	}
	public void setFileSuffName(List fileSuffName) {
		this.fileSuffName = fileSuffName;
	}
	public String getTempPath() {
		return temPath;
	}

	public void setTempPath(String tempPath) {
		this.temPath = tempPath;
	}

	public int getBufferSize() {
		return bufferSize;
	}

	public void setBufferSize(int bufferSize) {
		this.bufferSize = bufferSize;
	}

	public long getMaxSize() {
		return maxSize;
	}

	public void setMaxSize(long maxSize) {
		this.maxSize = maxSize;
	}

	public long getMax() {
		return max;
	}

	public void setMax(long max) {
		this.max = max;
	}

	public String getPath() {
		return path;
	}

	public void setPath(String path) {
		this.path = path;
	}

	public String getSavePath() {
		return savePath;
	}

	public void setSavePath(String savePath) {
		this.savePath = savePath;
	}
    /**
     * 上传文件
     * @param req 页面请求
     */
	public  void upload(HttpServletRequest req) {
		String realPath = req.getServletContext().getRealPath(path);
		String tempPath = req.getServletContext().getRealPath(temPath);
		File tempFile = new File(tempPath);
		File realFile = new File(realPath);
		if(!tempFile.exists()&&tempFile.isDirectory())
			tempFile.mkdirs();
		if(!realFile.exists()&&realFile.isDirectory()) {
			realFile.mkdirs();
		}
		DiskFileItemFactory factory = new DiskFileItemFactory();//创建工厂
		factory.setSizeThreshold(bufferSize);//设置缓冲区大小
		factory.setRepository(tempFile);//设置缓存目录
		ServletFileUpload upload = new ServletFileUpload(factory);//创建解析器
		upload.setProgressListener(new ProgressListener(){//监听事件
            @Override
            public void update(long pBytesRead, long pContentLength, int arg2) {
                System.out.println("文件大小为:" + pContentLength + ",当前已处理:" + pBytesRead);
            }
        });
		upload.setHeaderEncoding("UTF-8");//设置文件名编码格式
		upload.setFileSizeMax(maxSize);//设置单个文件大小
		upload.setSizeMax(max);//设置上传多个文件的总共的大小
		try {
			List item = upload.parseRequest(req);
			for (FileItem fileItem : item) {
				if(fileItem.isFormField()) {//普通数据
					String name = fileItem.getName();
					String value =fileItem.getString("utf-8");
					System.out.println(name+":"+value);
				}else {//文件
					String name = fileItem.getName();
					System.out.println(name);
					if(name==null||name.trim().equals("")) {
						continue;
					}
					name=name.substring(name.lastIndexOf("\\")+1);
					String suffname=name.substring(name.lastIndexOf(".")+1);//文件后缀名
					String saveName = creatFileName(name);
					String savePath = realPath+File.separator+saveName;
					System.out.println(savePath);
					this.savePath=savePath;
					if(fileSuffName!=null) {
						for (String fileSuff : fileSuffName) {
							if(suffname.equals(fileSuff)) {
								fileItem.write(new File(savePath));
							}
						}
					}else {
						      fileItem.write(new File(savePath));
					}
					fileItem.delete();
				}
			}
		} catch (FileUploadException e) {
			e.printStackTrace();
		} catch (UnsupportedEncodingException e) {
			e.printStackTrace();
		} catch (FileNotFoundException e) {
			e.printStackTrace();
		} catch (IOException e) {
			e.printStackTrace();
		} catch (Exception e) {
			e.printStackTrace();
		}finally {

		}
	}
	
	private String creatFileName(String name) {//生成唯一文件名
		return UUID.randomUUID().toString()+"_"+name;
	}
	/**
	 * 下载文件
	 * @param savaPath 文件绝对路径
	 * @param resp 响应
	 */
    public void download(String savaPath,HttpServletResponse resp) {
         String filename = savaPath.substring(savaPath.indexOf("_")+1);
       //设置响应头,告诉浏览器要下载的文件是否在浏览器中显示,inline表示内嵌显示,attachment表示弹出下载框
       resp.setHeader("Content-Disposition", "inline;filename="+filename);
       BufferedInputStream bis=null;
       OutputStream out=null;
       try {
	       bis = new BufferedInputStream(new FileInputStream(savaPath));
	       out = resp.getOutputStream();//获取输出流
	       int len=0;
	       while((len=bis.read())!=-1){
	       	out.write(len);//输出到客户端
	       }
           } catch (FileNotFoundException e) {
	          e.printStackTrace();
           }catch (IOException e) {
			e.printStackTrace();
		}finally {
			try {
				if(out!=null)out.close();
				if(bis!=null)bis.close();
			} catch (IOException e) {
				e.printStackTrace();
			}
		}
   }

}

你可能感兴趣的:(java基础)