@martin0207
2018-04-19T12:23:09.000000Z
字数 1244
阅读 784
Java学习
学到文件上传这里,使用Apache的FileUpload工具,地址链接
protected void doPost(HttpServletRequest request, HttpServletResponse response)throws ServletException, IOException {boolean isMultipart = ServletFileUpload.isMultipartContent(request);System.out.println(isMultipart);if (isMultipart) {ServletFileUpload fileUpload = new ServletFileUpload();InputStream is = null;FileOutputStream out = null;try {FileItemIterator itemIterator = fileUpload.getItemIterator(request);while (itemIterator.hasNext()) {FileItemStream stream = itemIterator.next();// 使用Multipart之后,说明使用字节流传递,所以需要将其转化为输入流处理is = stream.openStream();// 是否是普通的表单域if (stream.isFormField()) {// 如果是表单域,可以获取表单域的名称System.out.println(stream.getFieldName());// 通过Streams的asString方法,可以将流中的数据转换为StringSystem.out.println("value = " + Streams.asString(is));} else {// 如果不是表单域,则可以获取文件的名称String name = stream.getName();String path = request.getSession().getServletContext().getRealPath("/file");path = path + "/" + name.substring(name.lastIndexOf("\\") + 1, name.length());out = new FileOutputStream(path);System.out.println(path);byte[] bs = new byte[1024];int length = 0;while ((length = is.read(bs)) > 0) {out.write(bs, 0, length);}}}} catch (FileUploadException e) {// TODO Auto-generated catch blocke.printStackTrace();} finally {if (is != null) {is.close();}if (out != null) {out.close();}}}}