FileUpLoad文件上传组件详解

DiskFileItemFactory对象的工厂,可以设定缓冲区大小和存放临时文件目录。

voidsetRepository(java.io.File repository) 默认是System.getProperty("java.io.tmpdir"),即操作系统默认临时文件夹路径
          Sets the directory used to temporarily store files that are larger than the configured size threshold.
voidsetSizeThreshold(int sizeThreshold) 以字节为单位,默认是10K
          Sets the size threshold beyond which files are written directly to disk.

ServletFileUpload This class handles multiple files per single HTML widget, sent using multipart/mixed encoding type, as specified by RFC 1867. Use parseRequest(HttpServletRequest) to acquire a list of FileItems associated with a given HTML widget.

处理表单数据,将数据封装到 FileItem 对象中。

FileItem  用来封装表单中的元素和数据。

voiddelete() 手动删除临时文件
          Deletes the underlying storage for a file item, including deleting any associated temporary disk file.
byte[]get() 获取上传文件的二进制数组
          Returns the contents of the file item as an array of bytes.
StringgetContentType() 获取上传文件的文件类型
          Returns the content type passed by the browser or null if not defined.
StringgetFieldName() 获取组件的name属性
          Returns the name of the field in the multipart form corresponding to this file item.
InputStreamgetInputStream() 获取上传文件的输入流
          Returns an InputStream that can be used to retrieve the contents of the file.
StringgetName() 获取上传文件的文件名
          Returns the original filename in the client's filesystem, as provided by the browser (or other client software).
longgetSize() 获取上传文件的大小,字节为单位
          Returns the size of the file item.
StringgetString() 获取组件的value属性
          Returns the contents of the file item as a String, using the default character encoding.
StringgetString(java.lang.String encoding) 以某种编码形式解码,获取组件的value属性
          Returns the contents of the file item as a String, using the specified encoding.
booleanisFormField() 判断当前item是否是普通文本组件
          Determines whether or not a FileItem instance represents a simple form field.
booleanisInMemory() 判断文件是否存储在内存中
          Provides a hint as to whether or not the file contents will be read from memory.
voidwrite(java.io.File file) 将上传文件写出到服务器的硬盘上,参数指定文件
          A convenience method to write an uploaded item to disk.


例子:

jsp页面中

<form action="servlet/UploadServlet" enctype="multipart/form-data" method="post">
    <input type="text" name="userName" value="xxc">
    <input type="file" name="file">
    <input type="submit" value="上传">
</form>
在Servlet中

public void doPost(HttpServletRequest request, HttpServletResponse response)
			throws ServletException, IOException {
		 request.setCharacterEncoding("UTF-8");
		 DiskFileItemFactory factory = new DiskFileItemFactory();//对象的工厂,可以设定缓冲区大小和存放临时文件目录。
		 factory.setSizeThreshold(600);//参数是以字节为单位的int值,如果从没有调用该方法设置此临界值,将会采用系统默认值10KB。
		 factory.setRepository(new File(this.getServletContext().getRealPath("/temp")));//当上传文件超过上面设置的值时,就将临时文件存储在硬盘上。
		 
		 
		 ServletFileUpload upload = new ServletFileUpload(factory);//处理表单数据,将数据封装到 FileItem 对象中。
		 //upload.setHeaderEncoding("UTF-8");
		 String[] allowTypes = new String[]{"jpg","xls"}; //将服务器端所能接受的上传文件类型,写在一个数组里。
		 List<FileItem> fileItems = null;//用来封装表单中的元素和数据。构造函数时,需要传入一个request。
			try {
				fileItems = upload.parseRequest(request);
				Iterator<FileItem> iterator = fileItems.iterator();
				while(iterator.hasNext()){
					FileItem item = iterator.next();
					if(item.isFormField()){
						String field = item.getFieldName();//获取组件的name属性
						String value = item.getString("UTF-8");//参数可写编码,防止文本组件的值乱码
						//String name = item.getName();//这个应该是上传文件的文件名  当用于不是上传文件组件时候,一律返回null
					}else{
						 /**
						 * 上传方式一   这个方法看了源码之后大概意思是,首先它会进行判断,如果数据存在于内存中的就会象方式二这么上传数据,因为前面做了验证,只有小于600K的数据才
						 * 存在于内存中,如果数据不存在于内存中就采用类似方式三的方法进行上传数据,只不过源码中将输入流copy到输出流用的是IOUtils.copy(fis, fos);
						 * org.apache.commons.io.IOUtils;
						 * */
						String contentType = item.getContentType();//获取上传文件类型
						List<String> allowTypesList = Arrays.asList(allowTypes);//将数组转换为集合
						if(!allowTypesList.contains(contentType)){//用当前Item的文件类型和集合中的类型比较
							System.out.println("不符合上传类型");
							return;
						}
						
						
						
						String fileName = item.getName();//获取上传文件的文件名
						String filePath = this.getServletContext().getRealPath("/Files");//获取当前项目根目录下的Files文件夹的在服务器硬盘上的真实路径
						item.write(new File(filePath+"/"+fileName));
						
						
						/**上传方式二 */
						/*FileOutputStream fos = new FileOutputStream(filePath+"/"+fileName);
						Streams.copy(item.getInputStream(), fos, false);//将输入流拷贝到输出流,输入流是客户端传过来的,输出流是服务器端写到硬盘上的
						fos.close();*/
						//item.delete();//手动删除临时文件
						
						/**上传方式三  这种方式不推荐,因为文件过大就会导致内存溢出异常*/
						/*FileOutputStream fos = new FileOutputStream(filePath+"/"+fileName);
						byte[] buf = item.get();
						fos.write(buf);*/
					}
				}
			} catch (FileUploadException e) {
				e.printStackTrace();
			} catch (Exception e) {
				e.printStackTrace();
			}
		}
}



  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值