当前位置: 代码迷 >> 综合 >> 文件上传和enctype=multipart/form-data时文本框参数获取问题的解决及文件下载(servlet方式)
  详细解决方案

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

热度:51   发布时间:2023-10-21 15:42:58.0

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

        在进行文件上传时,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;

 

  相关解决方案