依赖Commons FileUpload原件完成文件上传

  • 在servlet3.0以下的版本上传文件依赖 Apache Commons FileUpload元件完成文件上传FileUpload depends on Commons IO。

  • 因此使用Apache Comms FileUpload元件上传需要依赖两个jar包。其Maven配置为:

<!-- https://mvnrepository.com/artifact/commons-fileupload/commons-fileupload -->
<dependency>
    <groupId>commons-fileupload</groupId>
    <artifactId>commons-fileupload</artifactId>
    <version>1.3.3</version>
</dependency>

Each file item has a number of properties that might be of interest for your application. For example, every item has a name and a content type, and can provide an InputStream to access its data. On the other hand, you may need to process items differently, depending upon whether the item is a regular form field - that is, the data came from an ordinary text box or similar HTML field - or an uploaded file. The FileItem interface provides the methods to make such a determination, and to access the data in the most appropriate manner.

FileUpload creates new file items using a FileItemFactory. This is what gives FileUpload most of its flexibility. The factory has ultimate control over how each item is created. The factory implementation that currently ships with FileUpload stores the item's data in memory or on disk, depending on the size of the item (i.e. bytes of data). However, this behavior can be customized to suit your application.

  • 对于上传的基本步骤比较固定将其封装为工具类:

package com.test.util;

import java.io.File;
import java.util.List;

import javax.servlet.ServletContext;
import javax.servlet.http.HttpServletRequest;

import org.apache.commons.fileupload.FileItem;
import org.apache.commons.fileupload.FileUploadException;
import org.apache.commons.fileupload.disk.DiskFileItemFactory;
import org.apache.commons.fileupload.servlet.ServletFileUpload;

/**
 * 封装用Apache Commons FileUpload 和 Commons IO 元件上传中
 * FileItem 的获取
 * @author QuLei
 */
public class UploadUtil {
	/**
	 * @param request  请求对象
	 * @param charSet  请求的字符集
	 * @return  返回FileItem 的集合
	 */
	public static List<FileItem> uploadUtil(HttpServletRequest request,String charSet){
		//获取工厂
		DiskFileItemFactory factory = new DiskFileItemFactory();
		//配置仓库(存放临时文件的目录)的位置
		ServletContext servletContext = request.getSession().getServletContext();
		File repository = (File) servletContext.getAttribute("javax.servlet.context.tempdir");
		factory.setRepository(repository);
		//创建解析请求的对象
		ServletFileUpload upload = new ServletFileUpload(factory);
		//设置文件的中文问题
		upload.setHeaderEncoding(charSet);
		try {
			//解析请求中的流信息
			List<FileItem> items = upload.parseRequest(request);
			return items;
		} catch (FileUploadException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
		return null;
	}
}
  • 通过以上的处理获取到一个File Item 的List对该List处理,需要判断表单域或文件流资源:

        FileItem item = null;
		List<FileItem> list = UploadUtil.uploadUtil(request, "utf-8");
        //遍历list判断出表单域元素并获取值
		for (FileItem fileItem : list) {
			if(fileItem.isFormField()){
                //获取表单域属性名
	        String fieldName = fileItem.getFieldName();
                //这里有两个方法,一个带参的和一个不带参的!要注意字符集,否则有中文乱码
				String tempStr = fileItem.getString("utf-8");
				logger.debug(fieldName+"获取到的参数为:"+tempStr);		
				if("shop".equals(fieldName)){
					shop = tempStr;
				}else if("price".equals(fieldName)){
					price = Double.parseDouble(tempStr);
				}else if("crement".equals(fieldName)){
					crement = tempStr;
				}else if("grade".equals(fieldName)){
					grade = Double.parseDouble(tempStr);
				}
			}else{
				item = fileItem;
			}
		}
        //获取上传的文件的名字(如:mn.jpg)
		path = item.getName();
 //文件域元素
//获取文件名
String fileName=item.getName();
//获取文件的流信息
InputStream in=item.getInputStream();
OutputStream out=new FileOutputStream(new File("d:/img/"+fileName));
byte[] b=new byte[8192];
int temp=0;
while((temp=in.read(b))!=-1){
	out.write(b,0,temp);
	}
out.flush();
out.close();
in.close();


//也可以直接用item直接输出到一个指定的路径
item.write(new File(dir,path));
  • 关于服务器资源获取的路径问题:

  • 使用ServletContext对象

  1. 获取方式:

    1. this.getServletContext()
    2. this.getServletConfig.getServletContext()
    3. request.getSession.getServletContext()       这三种方式获取的都是一个单例的对象   也称作:application对象
  2. 重要方法:

    1. getRealPath(路径)    获取WebRoot下所有资源的绝对路径,加不加  /  都代表绝对路径;且都是代表WebRoot与端口后之间差一个虚拟项目名(页面上所有的绝对路径都是相对于端口号之后)
    2. getResourceAsStream(路径)  这个路径必须写全,即从WebRoot开始往下写,否则找不到就返回null
    3. getResourcePath(目录地址)返回该目录下所有的资源集合路径    目录地址前面必须加  /   获得的结果是带有/的从WebRoot开始的路径集合 Set
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值