您的位置:首页 > 其它

利用commons-fileupload实现多个文件上传

2009-03-19 11:02 465 查看
Java代码



1. <html>

2. <head>

3. <meta http-equiv="Content-Type" content="text/html; charset=GB18030">

4. <title>File upload</title>

5. </head>

6. <body>

7. <form name="myform" action="demo2.jsp" method="post"

8. enctype="multipart/form-data">

9. File1:<br>

10. <input type="file" name="myfile"><br>

11. File2:<br>

12. <input type="file" name="myfile"><br>

13. <br>

14. <input type="submit" name="submit" value="Commit">

15. </form>

16. </body>

17. </html>

1. <html>
2. <head>
3.     <meta http-equiv="Content-Type" content="text/html; charset=GB18030">
4.     <title>File upload</title>
5. </head>
6. <body>
7.     <form name="myform" action="demo2.jsp" method="post"
8.        enctype="multipart/form-data">
9.        File1:<br>
10.        <input type="file" name="myfile"><br>
11.        File2:<br>
12.        <input type="file" name="myfile"><br>
13.        <br>
14.        <input type="submit" name="submit" value="Commit">
15.     </form>
16. </body>
17. </html>

Java代码



1. package com.zj.sample;

2.

3. import java.io.File;

4. import java.io.IOException;

5. import java.util.Iterator;

6. import java.util.List;

7.

8. import javax.servlet.ServletException;

9. import javax.servlet.http.HttpServlet;

10. import javax.servlet.http.HttpServletRequest;

11. import javax.servlet.http.HttpServletResponse;

12.

13. import org.apache.commons.fileupload.DiskFileUpload;

14. import org.apache.commons.fileupload.FileItem;

15. import org.apache.commons.fileupload.FileUploadException;

16. import org.apache.commons.fileupload.disk.DiskFileItemFactory;

17. import org.apache.commons.fileupload.servlet.ServletFileUpload;

18.

19. @SuppressWarnings("serial")

20. public class Upload extends HttpServlet {

21. private String uploadPath = "D://temp"; // 上传文件的目录

22. private String tempPath = "d://temp//buffer//"; // 临时文件目录

23. File tempPathFile;

24.

25. @SuppressWarnings("unchecked")

26. public void doPost(HttpServletRequest request, HttpServletResponse response)

27. throws IOException, ServletException {

28.

29. String msg = "";

30. DiskFileUpload fu = new DiskFileUpload();

31. // 设置允许用户上传文件大小,单位:字节

32. // fu.setSizeMax(10000000);

33. // 设置最多只允许在内存中存储的数据,单位:字节

34. // fu.setSizeThreshold(4096);

35. // 设置一旦文件大小超过getSizeThreshold()的值时数据存放在硬盘的目录

36. //(临时存放目录,文件上传完毕后有办法清除它吗?)

37. fu.setRepositoryPath("D://TEMP");

38. //开始读取上传信息

39. List fileItems = null;

40. try {

41. fileItems = fu.parseRequest(request);

42. } catch (FileUploadException e1) {

43. // TODO 自动生成 catch 块

44. e1.printStackTrace();

45. }

46. // 依次处理每个上传的文件

47. Iterator iter = fileItems.iterator();

48. while (iter.hasNext())

49. {

50. FileItem item = (FileItem) iter.next();

51. //忽略其他不是文件域的所有表单信息

52. if (!item.isFormField())

53. {

54. String name = item.getName();//获取上传的文件名

55. long size = item.getSize();//获取上传的文件大小(字节为单位)

56. if ((name == null || name.equals("")) && size == 0)

57. continue;//跳到while检查条件

58.

59. System.out.println("<tr>");

60. System.out.println("<td>" + name + "</td>");

61. System.out.println("<td>" + size + "</td>");

62.

63. //以下为文件名处理,将上传的文件保存在项目所在目录下。

64. //获取文件名字符串的长度

65. int end = name.length();

66. //返回在此字符串中最右边出现的指定子字符串的索引。

67. int begin = name.lastIndexOf("//");

68. File savedFile = new File("c://TEMP", name.substring(

69. begin + 1, end));

70. try {

71. item.write(savedFile);

72. } catch (Exception e) {

73. // TODO 自动生成 catch 块

74. e.printStackTrace();

75. }

76. }

77. }

78.

79.

80. try {

81. // Create a factory for disk-based file items

82. DiskFileItemFactory factory = new DiskFileItemFactory();

83.

84. // Set factory constraints

85. factory.setSizeThreshold(4096); // 设置缓冲区大小,这里是4kb

86. factory.setRepository(tempPathFile);// 设置缓冲区目录

87.

88. // Create a new file upload handler

89. ServletFileUpload upload = new ServletFileUpload(factory);

90.

91. // Set overall request size constraint

92. upload.setSizeMax(4194304); // 设置最大文件尺寸,这里是4MB

93.

94. List<FileItem> items = upload.parseRequest(request);// 得到所有的文件

95. Iterator<FileItem> i = items.iterator();

96. while (i.hasNext()) {

97. FileItem fi = (FileItem) i.next();

98. String fileName = fi.getName();

99. if (fileName != null) {

100. File fullFile = new File(fi.getName());

101. File savedFile = new File(uploadPath, fullFile.getName());

102. fi.write(savedFile);

103. }

104. }

105. System.out.print("upload succeed");

106. } catch (Exception e) {

107. // 可以跳转出错页面

108. e.printStackTrace();

109. }

110. }

111.

112. public void init() throws ServletException {

113. File uploadFile = new File(uploadPath);

114. if (!uploadFile.exists()) {

115. uploadFile.mkdirs();

116. }

117. File tempPathFile = new File(tempPath);

118. if (!tempPathFile.exists()) {

119. tempPathFile.mkdirs();

120. }

121. }

122. }
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: