Flex+Java Servlet文件上传实例
资源都是来自网上。本实例将展示使用Flex和java servlet上传文件。
事前准备就是到http://commons.apache.org下载common-fileupload-1.1.1.jar以及common-io-1.2.jar两个包。
前台Flex代码:
Java代码
1.<?xml version="1.0" encoding="utf-8"?>
2.<mx:Application xmlns:mx="http://www.adobe.com/2006/mxml" layout="absolute" xmlns="*" creationComplete="init();">
3.<mx:Script>
4.<![CDATA[
5.import flash.net.FileReference;
6.import mx.controls.Alert;
7.import mx.events.CloseEvent;
8.import flash.events.*;
9.
10.private var file: FileReference;
11.
12.private function init(): void{
13.Security.allowDomain("*");
14.file = new FileReference();
15.file.addEventListener(ProgressEvent.PROGRESS, onProgress);
16.file.addEventListener(Event.SELECT, onSelect);
17.file.addEventListener(Event.COMPLETE, completeHandle);
18.}
19.
20.private function completeHandle(event:Event):void{
21. Alert.show("恭喜你,上传成功");
22.}
23.
24.private function upload(): void{
25.var imageTypes:FileFilter = new FileFilter("Images (*.jpg, *.jpeg, *.png)", "*.jpg;*.jpeg;*.png");
26.var allTypes:Array = new Array(imageTypes);
27.file.browse(allTypes);
28.file.browse();
29.}
30.private function onSelect(e: Event): void{
31.Alert.show("上传 " + file.name + " (共 "+Math.round(file.size)+" 字节)?",
32."确认上传",
33.Alert.YES|Alert.NO,
34.null,
35.proceedWithUpload);
36.}
37.
38.private function onProgress(e: ProgressEvent): void{
39.lbProgress.text = " 已上传 " + e.bytesLoaded
40.+ " 字节,共 " + e.bytesTotal + " 字节";
41.var proc: uint = e.bytesLoaded / e.bytesTotal * 100;
42.bar.setProgress(proc, 100);
43.bar.label= "当前进度: " + " " + proc + "%";
44.}
45.
46.private function proceedWithUpload(e: CloseEvent): void{
47.if (e.detail == Alert.YES){
48.var request: URLRequest = new URLRequest("http://localhost:8080/FileUploaded/FileUploaded");
49.try {
50.file.upload(request);
51.} catch (error:Error) {
52.trace("上传失败");
53.}
54.
55.}
56.}
57.]]>
58.</mx:Script>
59.
60.<mx:Canvas width="100%" height="100%" x="10" y="170" fontSize="15">
61.<mx:VBox width="100%" horizontalAlign="center">
62.<mx:Label id="lbProgress" text="上传"/>
63.<mx:ProgressBar id="bar" labelPlacement="bottom" themeColor="#F20D7A"
64.minimum="0" visible="true" maximum="100" label="当前进度: 0%"
65.direction="right" mode="manual" width="200"/>
66.
67.<mx:Button label="上传文件" click="upload();"/>
68.</mx:VBox>
69.</mx:Canvas>
70.</mx:Application>
<?xml version="1.0" encoding="utf-8"?>
<mx:Application xmlns:mx="http://www.adobe.com/2006/mxml" layout="absolute" xmlns="*" creationComplete="init();">
<mx:Script>
<![CDATA[
import flash.net.FileReference;
import mx.controls.Alert;
import mx.events.CloseEvent;
import flash.events.*;
private var file: FileReference;
private function init(): void{
Security.allowDomain("*");
file = new FileReference();
file.addEventListener(ProgressEvent.PROGRESS, onProgress);
file.addEventListener(Event.SELECT, onSelect);
file.addEventListener(Event.COMPLETE, completeHandle);
}
private function completeHandle(event:Event):void{
Alert.show("恭喜你,上传成功");
}
private function upload(): void{
var imageTypes:FileFilter = new FileFilter("Images (*.jpg, *.jpeg, *.png)", "*.jpg;*.jpeg;*.png");
var allTypes:Array = new Array(imageTypes);
file.browse(allTypes);
file.browse();
}
private function onSelect(e: Event): void{
Alert.show("上传 " + file.name + " (共 "+Math.round(file.size)+" 字节)?",
"确认上传",
Alert.YES|Alert.NO,
null,
proceedWithUpload);
}
private function onProgress(e: ProgressEvent): void{
lbProgress.text = " 已上传 " + e.bytesLoaded
+ " 字节,共 " + e.bytesTotal + " 字节";
var proc: uint = e.bytesLoaded / e.bytesTotal * 100;
bar.setProgress(proc, 100);
bar.label= "当前进度: " + " " + proc + "%";
}
private function proceedWithUpload(e: CloseEvent): void{
if (e.detail == Alert.YES){
var request: URLRequest = new URLRequest("http://localhost:8080/FileUploaded/FileUploaded");
try {
file.upload(request);
} catch (error:Error) {
trace("上传失败");
}
}
}
]]>
</mx:Script>
<mx:Canvas width="100%" height="100%" x="10" y="170" fontSize="15">
<mx:VBox width="100%" horizontalAlign="center">
<mx:Label id="lbProgress" text="上传"/>
<mx:ProgressBar id="bar" labelPlacement="bottom" themeColor="#F20D7A"
minimum="0" visible="true" maximum="100" label="当前进度: 0%"
direction="right" mode="manual" width="200"/>
<mx:Button label="上传文件" click="upload();"/>
</mx:VBox>
</mx:Canvas>
</mx:Application>
http://localhost:8080/FileUploaded/FileUploaded就是你自己写的servlet的路径了。
接下来写的是Java Servlet:
Java代码
1.package upload;
2.import java.io.File;
3.import java.io.IOException;
4.import java.io.PrintWriter;
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.FileItem;
14.import org.apache.commons.fileupload.FileUploadException;
15.import org.apache.commons.fileupload.disk.DiskFileItemFactory;
16.import org.apache.commons.fileupload.servlet.ServletFileUpload;
17.
18./**
19. *
20. * @author crystal
21. */
22.public class FileUploaded extends HttpServlet {
23.
24. /**
25. * Processes requests for both HTTP <code>GET</code> and <code>POST</code> methods.
26. * @param request servlet request
27. * @param response servlet response
28. */
29. // 定义文件的上传路径
30.
31. private String uploadPath = "d:\\a\";
32.
33.// 限制文件的上传大小
34.
35. private int maxPostSize = 100 * 1024 * 1024;
36.
37. public FileUploaded() {
38. super();
39. }
40.
41. public void destroy() {
42. super.destroy();
43. }
44.
45. protected void processRequest(HttpServletRequest request, HttpServletResponse response)
46. throws ServletException, IOException {
47. System.out.println("Access !");
48. response.setContentType("text/html;charset=UTF-8");
49. PrintWriter out = response.getWriter();
50.
51.//保存文件到服务器中
52.
53. DiskFileItemFactory factory = new DiskFileItemFactory();
54. factory.setSizeThreshold(4096);
55. ServletFileUpload upload = new ServletFileUpload(factory);
56. upload.setSizeMax(maxPostSize);
57. try {
58. List fileItems = upload.parseRequest(request);
59. Iterator iter = fileItems.iterator();
60. while (iter.hasNext()) {
61. FileItem item = (FileItem) iter.next();
62. if (!item.isFormField()) {
63. String name = item.getName();
64. System.out.println(name);
65. try {
66. item.write(new File(uploadPath + name));
67. // SaveFile s = new SaveFile();
68.
69. // s.saveFile(name);
70.
71. } catch (Exception e) {
72. e.printStackTrace();
73. }
74. }
75. }
76. } catch (FileUploadException e) {
77. e.printStackTrace();
78. System.out.println(e.getMessage() + "结束");
79. }
80. }
81.
82. // <editor-fold defaultstate="collapsed" desc="HttpServlet methods. Click on the + sign on the left to edit the code.">
83.
84. /**
85. * Handles the HTTP <code>GET</code> method.
86. * @param request servlet request
87. * @param response servlet response
88. */
89. protected void doGet(HttpServletRequest request, HttpServletResponse response)
90. throws ServletException, IOException {
91. processRequest(request, response);
92. }
93.
94. /**
95. * Handles the HTTP <code>POST</code> method.
96. * @param request servlet request
97. * @param response servlet response
98. */
99. protected void doPost(HttpServletRequest request, HttpServletResponse response)
100. throws ServletException, IOException {
101. processRequest(request, response);
102. }
103.
104. /**
105. * Returns a short description of the servlet.
106. */
107. public String getServletInfo() {
108. return "Short description";
109. }
110. // </editor-fold>
111.
112.}
package upload;
import java.io.File;
import java.io.IOException;
import java.io.PrintWriter;
import java.util.Iterator;
import java.util.List;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import org.apache.commons.fileupload.FileItem;
import org.apache.commons.fileupload.FileUploadException;
import org.apache.commons.fileupload.disk.DiskFileItemFactory;
import org.apache.commons.fileupload.servlet.ServletFileUpload;
/**
*
* @author crystal
*/
public class FileUploaded extends HttpServlet {
/**
* Processes requests for both HTTP <code>GET</code> and <code>POST</code> methods.
* @param request servlet request
* @param response servlet response
*/
// 定义文件的上传路径
private String uploadPath = "d:\\a\";
// 限制文件的上传大小
private int maxPostSize = 100 * 1024 * 1024;
public FileUploaded() {
super();
}
public void destroy() {
super.destroy();
}
protected void processRequest(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
System.out.println("Access !");
response.setContentType("text/html;charset=UTF-8");
PrintWriter out = response.getWriter();
//保存文件到服务器中
DiskFileItemFactory factory = new DiskFileItemFactory();
factory.setSizeThreshold(4096);
ServletFileUpload upload = new ServletFileUpload(factory);
upload.setSizeMax(maxPostSize);
try {
List fileItems = upload.parseRequest(request);
Iterator iter = fileItems.iterator();
while (iter.hasNext()) {
FileItem item = (FileItem) iter.next();
if (!item.isFormField()) {
String name = item.getName();
System.out.println(name);
try {
item.write(new File(uploadPath + name));
// SaveFile s = new SaveFile();
// s.saveFile(name);
} catch (Exception e) {
e.printStackTrace();
}
}
}
} catch (FileUploadException e) {
e.printStackTrace();
System.out.println(e.getMessage() + "结束");
}
}
// <editor-fold defaultstate="collapsed" desc="HttpServlet methods. Click on the + sign on the left to edit the code.">
/**
* Handles the HTTP <code>GET</code> method.
* @param request servlet request
* @param response servlet response
*/
protected void doGet(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
processRequest(request, response);
}
/**
* Handles the HTTP <code>POST</code> method.
* @param request servlet request
* @param response servlet response
*/
protected void doPost(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
processRequest(request, response);
}
/**
* Returns a short description of the servlet.
*/
public String getServletInfo() {
return "Short description";
}
// </editor-fold>
}
如果使得你的Servlet被访问,你还需要在WEB-INF/web.xml 添加如下的xml语句:[在<web-app>中]
Java代码
1.<!-- For file uploaded -->
2. <servlet>
3. <servlet-name>FileUploaded</servlet-name>
4. <servlet-class>upload.FileUploaded</servlet-class>
5. </servlet>
6.
7. <servlet-mapping>
8. <servlet-name>FileUploaded</servlet-name>
9. <url-pattern>/FileUploaded</url-pattern>
10. </servlet-mapping>
<!-- For file uploaded -->
<servlet>
<servlet-name>FileUploaded</servlet-name>
<servlet-class>upload.FileUploaded</servlet-class>
</servlet>
<servlet-mapping>
<servlet-name>FileUploaded</servlet-name>
<url-pattern>/FileUploaded</url-pattern>
</servlet-mapping>
效果图: