[关闭]
@martin0207 2018-04-19T12:23:09.000000Z 字数 1244 阅读 744

Java学习,文件上传

Java学习


学到文件上传这里,使用Apache的FileUpload工具,地址链接

  1. protected void doPost(HttpServletRequest request, HttpServletResponse response)
  2. throws ServletException, IOException {
  3. boolean isMultipart = ServletFileUpload.isMultipartContent(request);
  4. System.out.println(isMultipart);
  5. if (isMultipart) {
  6. ServletFileUpload fileUpload = new ServletFileUpload();
  7. InputStream is = null;
  8. FileOutputStream out = null;
  9. try {
  10. FileItemIterator itemIterator = fileUpload.getItemIterator(request);
  11. while (itemIterator.hasNext()) {
  12. FileItemStream stream = itemIterator.next();
  13. // 使用Multipart之后,说明使用字节流传递,所以需要将其转化为输入流处理
  14. is = stream.openStream();
  15. // 是否是普通的表单域
  16. if (stream.isFormField()) {
  17. // 如果是表单域,可以获取表单域的名称
  18. System.out.println(stream.getFieldName());
  19. // 通过Streams的asString方法,可以将流中的数据转换为String
  20. System.out.println("value = " + Streams.asString(is));
  21. } else {
  22. // 如果不是表单域,则可以获取文件的名称
  23. String name = stream.getName();
  24. String path = request.getSession().getServletContext().getRealPath("/file");
  25. path = path + "/" + name.substring(name.lastIndexOf("\\") + 1, name.length());
  26. out = new FileOutputStream(path);
  27. System.out.println(path);
  28. byte[] bs = new byte[1024];
  29. int length = 0;
  30. while ((length = is.read(bs)) > 0) {
  31. out.write(bs, 0, length);
  32. }
  33. }
  34. }
  35. } catch (FileUploadException e) {
  36. // TODO Auto-generated catch block
  37. e.printStackTrace();
  38. } finally {
  39. if (is != null) {
  40. is.close();
  41. }
  42. if (out != null) {
  43. out.close();
  44. }
  45. }
  46. }
  47. }
添加新批注
在作者公开此批注前,只有你和作者可见。
回复批注