public void upload(HttpServletRequest request,HttpServletResponse response){ DiskFileItemFactory factory = new DiskFileItemFactory(); factory.setSizeThreshold(1024*500); File tempDIrectory = new File("d:\\tempDirectory"); factory.setRepository(tempDIrectory); //create a new file upload handler ServletFileUpload upload = new ServletFileUpload(factory); /set overall request size constraint upload.setFileSizeMax(1024*1024*5); //parse the request try { List<FileItem> items = upload.parseRequest(request); //遍历items: for(FileItem item: items){ if(item.isFormField()){ String name = item.getFieldName(); String value = item.getString("utf-8"); System.out.println(name + ":" + value); } //若是文件域则把文件保存到d:\\files 目录下 else{ String fieldName = item.getFieldName(); String fileName = item.getName(); String contentType = item.getContentType(); long sizeInBytes = item.getSize(); InputStream in = item.getInputStream(); byte [] buffer = new byte[1024]; int len = 0; fileName = "d:\\files\\" + fileName; OutputStream out = new FileOutputStream(fileName); while((len = in.read(buffer)) != -1){ out.write(buffer, 0, len); } out.close(); in.close(); } } }catch (FileUploadException e) { } }
时间: 2024-12-06 09:11:20