zoukankan      html  css  js  c++  java
  • 使用ServletFileUpload实现上传

    1.首先我们应该为上传的文件建一个存放的位置,一般位置分为暂时和真是目录,那我们就须要获取这俩个目录的绝对路径,在servlet中我们能够这样做

    		ServletContext application = this.getServletContext();
    		String tempDirectory = application.getRealPath(Constant.TEMP_DIRECTORY) + "/";
    		String realDirectory = application.getRealPath(Constant.REAL_DIRECTORY) + "/";

    然后建立文件工厂即仓库一个參数表示存放多大后flush,

    		FileItemFactory factory = new DiskFileItemFactory(Constant.SIZE_THRESHOLD,new File(tempDirectory));
    		ServletFileUpload upload = new ServletFileUpload(factory);
    2.对上传的文件进行设定

    		upload.setSizeMax(500*1024*1024);//设置该次上传最大值为500M
    3,.解析请求正文,获取上传文件,不抛出异常则写入真是路径

    List<FileItem> list = upload.parseRequest(request);
    			Iterator<FileItem> iter = list.iterator();
    			while (iter.hasNext()) {
    				FileItem item = iter.next();
    				//item.isFormField()用来推断当前对象是否是file表单域的数据  假设返回值是true说明不是 就是普通表单域
    				if(item.isFormField()){
    					System.out.println( "普通表单域" +item.getFieldName());
    					System.out.println(item.getString("utf-8"));
    
    				}else{
    					//System.out.println("file表单域" + item.getFieldName());
    					/*
    					 * 仅仅有file表单域才将该对象中的内容写到真实目录中 
    					 */
    					String lastpath = item.getName();//获取上传文件的名称
    					lastpath = lastpath.substring(lastpath.lastIndexOf("."));
    					String filename = UUID.randomUUID().toString().replace("-", "") + lastpath;
    					item.write(new File(realDirectory+filename));






  • 相关阅读:
    [py]函数小结
    [py]class的特殊方法
    [py]数据描述符优先级
    [py]python中__new__作用
    [py]django重置密码
    [py]多态的理解
    [py]类属性和实例属性
    【转】比较详细的Asp伪静态化方法及Asp静态化探讨
    VB6 XArrayDB | Xarray ReDim 用法
    vb6 使用msxml2.serverxmlhttp 请求HTTP
  • 原文地址:https://www.cnblogs.com/mfrbuaa/p/3910820.html
Copyright © 2011-2022 走看看