java文件的上传与下载
post是以流的方式发送给服务器,服务器也只能用流的方式接收
//接收post请求,要用接受流的方式 ServletInputStream inputStream = req.getInputStream(); byte[] buffer = new byte[1024000]; int read = inputStream.read(buffer); System.out.println(read); System.out.println(new String(buffer,0,read));
//首先判断上传的数据是否是多段数据(只有多段数据才是文件上传) if(ServletFileUpload.isMultipartContent(req)){ //创建fileitemFactory工厂实现类 FileItemFactory fileitemFactory = new DiskFileItemFactory(); //创建用于解析上传数据的工具类 ServletFileUpload servletFileUpload = new ServletFileUpload(fileitemFactory); //解析上传的数据,得到每一个表单项 try { List<FileItem> fileItems = servletFileUpload.parseRequest(req); for (FileItem fileItem : fileItems) { //判断是否为普通表单数据,true代表是 false代表不是 if (fileItem.isFormField()){ System.out.println("表单项的name值"+fileItem.getFieldName()); System.out.println("表单项的value值"+fileItem.getString("UTF-8")); }else { System.out.println("表单项的name值"+fileItem.getFieldName()); System.out.println("上传的文件名"+fileItem.getName()); try { fileItem.write(new File("D:\\"+fileItem.getName())); } catch (Exception e) { e.printStackTrace(); } } } } catch (FileUploadException e) { e.printStackTrace(); }