文件上传和enctype="multipart/form-data"时文本框参数获取问题的解决及文件下载(servlet方式)

        场景:在实现文件上传功能的同时还要向后台传递参数

        在进行文件上传时,form表单需要设置enctype="multipart/form-data"(指定传输数据为二进制类型),而设置后在后台controller(Servlet)中用方法request.getParameter("")获取到的参数值为null,那么就不能使用这种方式传递。

        以下代码提供解决思路:

使用commons-upload-xxx.jar、commons-io-xxx.jar包的文件上传核心代码:

// 在解析请求之前先判断请求类型是否为文件上传类型
boolean isMultipart = ServletFileUpload.isMultipartContent(request);
// 文件上传处理工厂
FileItemFactory factory = new DiskFileItemFactory();
// 创建文件上传处理器
ServletFileUpload upload = new ServletFileUpload(factory);
// 开始解析请求信息
List items = null;
try {
    items = upload.parseRequest(request);
} catch (FileUploadException e) {
    e.printStackTrace();
}
Iterator iter = items.iterator();
while (iter.hasNext()) {
    FileItem item = (FileItem) iter.next();
    //item.isFormField()返回true说明是文本框参数,普通输入项的数据
    if (item.isFormField()){
        String fieldName = item.getFieldName();//
	String value = item.getString("UTF-8");//.getString("encType")乱码问题的解决
	request.setAttribute(fieldName, value);   

    }else {
        //文件数据
        String fileName = item.getName();
        String suffix = fileName.substring(fileName.lastIndexOf(".") + 1);
	//UUID生成唯一的文件名			
        String uploadFileName = UUID.randomUUID()+ "." + suffix;
        //服务器下的某个位置
        String path = "/appDate/fileUpload";
        File file = new File(path);
        if (!file.exists()) {
	    file.mkdirs();
        }
				
        // 获取item中的上传文件的输入流
        InputStream in = item.getInputStream();
        // 创建一个文件输出流
        FileOutputStream out = new FileOutputStream(path+"/"+uploadFileName);
        // 创建一个缓冲区
        byte buffer[] = new byte[1024];
        // 判断输入流中的数据是否已经读完的标识
        int len = 0;
        // 循环将输入流读入到缓冲区当中,(len=in.read(buffer))>0就表示in里面还有数据
        while ((len = in.read(buffer)) > 0) {
            // 使用FileOutputStream输出流将缓冲区的数据写入到指定的目录
            out.write(buffer, 0, len);
        }
        // 关闭输入流
        in.close();
        in=null;
        // 关闭输出流
        out.close();
        out=null;
        // 删除处理文件上传时生成的临时文件
        item.delete();				 
    }
}

文件下载则是从服务器传输文件到客户端:

// 输入流读取服务器上文件
File file = new File("path")
InputStream in = new FileInputStream(file);
// 创建一个文件输出流
FileOutputStream out = new FileOutputStream();
// 创建一个缓冲区
byte buffer[] = new byte[1024];
// 判断输入流中的数据是否已经读完的标识
int len = 0;
// 循环将输入流读入到缓冲区当中,(len=in.read(buffer))>0就表示in里面还有数据
while ((len = in.read(buffer)) > 0) {
    // 使用FileOutputStream输出流将缓冲区的数据写入到指定的目录
    out.write(buffer, 0, len);
}
// 关闭输入流
in.close();
in=null;
// 关闭输出流
out.close();
out=null;

 

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值