- 浏览: 39359 次
- 性别:
- 来自: 上海
文章分类
最新评论
在Adobe的Flex RIA编程环境下,是无法读取本地文件的(据我所知),但是我们可以依赖于Flex调用后台的代码实现文件上传功能,我这里是利用Flex的URLRequest来向java的Servlet传送一个Http请求(Servlet集成自HttpServlet ,已实现文件上传功能),而Servlet响应请求之后会利用Apcahe的开源Jar包(org.apache.commons.fileupload.servlet.ServletFileUpload类)完成文件的生成。 通过以上原理就可以利用Flex+java实现文件上传。(这里也是参考了网上的一些文章)
java Servlet 代码
Java代码
1.package com.yyhy.java.util;
2.
3.//多文件上传的Java端的类
4.import javax.servlet.http.HttpServlet;
5.import javax.servlet.http.HttpServletRequest;
6.import javax.servlet.http.HttpServletResponse;
7.import javax.servlet.ServletException;
8.import java.util.List;
9.import java.util.Iterator;
10.import java.io.File;
11.import java.io.IOException;
12.import java.io.UnsupportedEncodingException;
13.import java.net.URLDecoder;
14.import org.apache.commons.fileupload.FileUploadException;
15.import org.apache.commons.fileupload.disk.DiskFileItemFactory;
16.import org.apache.commons.fileupload.servlet.ServletFileUpload;
17.import org.apache.commons.fileupload.FileItem;
18.import org.apache.log4j.Logger;
19.import org.apache.commons.lang.ObjectUtils;
20.import org.springframework.context.ApplicationContext;
21.import org.springframework.context.support.ClassPathXmlApplicationContext;
22.
23.
24.public class FileUploadAction extends HttpServlet {
25.
26. // 限制文件的上传大小
27. private int maxPostSize = 100 * 1024 * 1024;
28. //文件上传地址
29. private String uploadPath;
30.
31. public FileUploadAction() {
32. //从配置文件中取得文件上传地址
33. setUploadPath();
34. }
35. public String getUploadPath() {
36. return uploadPath;
37. }
38. public void setUploadPath() {
39. //从配置文件中取得文件上传地址
40. ApplicationContext context = new ClassPathXmlApplicationContext("applicationContext.xml");
41. ServerAddress serverAddressBean=(ServerAddress)context.getBean("ServerAddressBean");
42. this.uploadPath = serverAddressBean.getUploadPath().trim();
43. }
44. // 文件上传
45. public void service(HttpServletRequest request, HttpServletResponse response)
46. throws ServletException
47. {
48. this.doUploadAdd(request, response);
49. }
50.
51. private void logger(String info) {
52. System.out.println(info);
53. }
54.
55. protected void doGet(HttpServletRequest request, HttpServletResponse response)
56. throws ServletException, IOException {
57. doUploadAdd(request, response);
58. }
59.
60. protected void doPost(HttpServletRequest request, HttpServletResponse response)
61. throws ServletException, IOException {
62. doUploadAdd(request, response);
63. }
64.
65. private void doUploadAdd(HttpServletRequest request,
66. HttpServletResponse response) throws ServletException {
67. logger("begin to upload");
68. try {
69. request.setCharacterEncoding("UTF-8");// 防止文件名称带有汉字后传到服务器乱码
70. //建立文件夹
71. this.makeDir(uploadPath);
72. } catch (UnsupportedEncodingException e) {
73. // TODO Auto-generated catch block
74. e.printStackTrace();
75. }
76. saveFiletoServer(request,response,uploadPath);
77. }
78.
79. private void doUploadDelete(HttpServletRequest request,HttpServletResponse response) throws ServletException
80. {
81. String dirtyStr = "";//需要删除的文件名(单个文件)或文件夹名列表
82. try
83. {
84. if (request.getParameter("dirtyStr") != null) {
85. dirtyStr=URLDecoder.decode(request.getParameter("dirtyStr"),"utf-8");//前台ENCODE,后台DECODE
86. logger("删除的文件(夹)为:" + dirtyStr);
87. }
88. }
89. catch (Exception e) {
90. // TODO Auto-generated catch block
91. logger(e.getMessage());
92. }
93.
94. try {
95. new DeleteFiles().DeleteModifyFiles(dirtyStr, uploadPath);
96. } catch (Exception e) {
97. logger(e.getMessage());
98. }
99. }
100. //保存文件到服务器中
101. private void saveFiletoServer(HttpServletRequest request,HttpServletResponse response,String uploadPath)
102. {
103. // 操作文件
104. response.setContentType("text/html; charset=UTF-8");
105. DiskFileItemFactory factory = new DiskFileItemFactory();
106. factory.setSizeThreshold(1024 * 4);
107. ServletFileUpload upload = new ServletFileUpload(factory);
108. upload.setFileSizeMax(maxPostSize);
109. logger("request========" + ObjectUtils.toString(request));
110. List fileItems = null;
111. try {
112. fileItems = upload.parseRequest(request);
113. logger("============" + ObjectUtils.toString(fileItems));
114. Iterator iter = fileItems.iterator();
115. while (iter.hasNext()) {
116. FileItem item = (FileItem) iter.next();
117. log(item.toString());
118. if (!item.isFormField()) {
119. String name = item.getName();
120. logger("上传的文件名 = " + name);
121. try {
122. item.write(new File(uploadPath + name));
123. } catch (Exception ex) {
124. logger(ex.getMessage());
125. }
126. }
127. }
128. } catch (FileUploadException ex1) {
129. logger("FileUploadException->" + ex1.getMessage());
130. }
131. }
132. // 建立文件夹路径
133. private boolean makeDir(String uploadPath) {
134. boolean isOK = false;
135. try {
136. File file = new File(uploadPath);
137. file.mkdirs();
138. isOK = true;
139. } catch (Exception e) {
140. isOK = false;
141. } finally {
142. return isOK;
143. }
144. }
145. // 建立文件夹路径
146. private boolean makeDirs(String uploadPath, String newDocStr) {
147. boolean isOK = false;
148. File file;
149. String[] temp;
150. try {
151. temp = newDocStr.split(",");
152. for (int i = 0; i < temp.length; i++) {
153. file = new File(uploadPath + temp[i] + "\\");
154. file.mkdirs();
155. }
156. isOK = true;
157. } catch (Exception e) {
158. isOK = false;
159. } finally {
160. return isOK;
161. }
162. }
163.}
package com.yyhy.java.util;
//多文件上传的Java端的类
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.ServletException;
import java.util.List;
import java.util.Iterator;
import java.io.File;
import java.io.IOException;
import java.io.UnsupportedEncodingException;
import java.net.URLDecoder;
import org.apache.commons.fileupload.FileUploadException;
import org.apache.commons.fileupload.disk.DiskFileItemFactory;
import org.apache.commons.fileupload.servlet.ServletFileUpload;
import org.apache.commons.fileupload.FileItem;
import org.apache.log4j.Logger;
import org.apache.commons.lang.ObjectUtils;
import org.springframework.context.ApplicationContext;
import org.springframework.context.support.ClassPathXmlApplicationContext;
public class FileUploadAction extends HttpServlet {
// 限制文件的上传大小
private int maxPostSize = 100 * 1024 * 1024;
//文件上传地址
private String uploadPath;
public FileUploadAction() {
//从配置文件中取得文件上传地址
setUploadPath();
}
public String getUploadPath() {
return uploadPath;
}
public void setUploadPath() {
//从配置文件中取得文件上传地址
ApplicationContext context = new ClassPathXmlApplicationContext("applicationContext.xml");
ServerAddress serverAddressBean=(ServerAddress)context.getBean("ServerAddressBean");
this.uploadPath = serverAddressBean.getUploadPath().trim();
}
// 文件上传
public void service(HttpServletRequest request, HttpServletResponse response)
throws ServletException
{
this.doUploadAdd(request, response);
}
private void logger(String info) {
System.out.println(info);
}
protected void doGet(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
doUploadAdd(request, response);
}
protected void doPost(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
doUploadAdd(request, response);
}
private void doUploadAdd(HttpServletRequest request,
HttpServletResponse response) throws ServletException {
logger("begin to upload");
try {
request.setCharacterEncoding("UTF-8");// 防止文件名称带有汉字后传到服务器乱码
//建立文件夹
this.makeDir(uploadPath);
} catch (UnsupportedEncodingException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
saveFiletoServer(request,response,uploadPath);
}
private void doUploadDelete(HttpServletRequest request,HttpServletResponse response) throws ServletException
{
String dirtyStr = "";//需要删除的文件名(单个文件)或文件夹名列表
try
{
if (request.getParameter("dirtyStr") != null) {
dirtyStr=URLDecoder.decode(request.getParameter("dirtyStr"),"utf-8");//前台ENCODE,后台DECODE
logger("删除的文件(夹)为:" + dirtyStr);
}
}
catch (Exception e) {
// TODO Auto-generated catch block
logger(e.getMessage());
}
try {
new DeleteFiles().DeleteModifyFiles(dirtyStr, uploadPath);
} catch (Exception e) {
logger(e.getMessage());
}
}
//保存文件到服务器中
private void saveFiletoServer(HttpServletRequest request,HttpServletResponse response,String uploadPath)
{
// 操作文件
response.setContentType("text/html; charset=UTF-8");
DiskFileItemFactory factory = new DiskFileItemFactory();
factory.setSizeThreshold(1024 * 4);
ServletFileUpload upload = new ServletFileUpload(factory);
upload.setFileSizeMax(maxPostSize);
logger("request========" + ObjectUtils.toString(request));
List fileItems = null;
try {
fileItems = upload.parseRequest(request);
logger("============" + ObjectUtils.toString(fileItems));
Iterator iter = fileItems.iterator();
while (iter.hasNext()) {
FileItem item = (FileItem) iter.next();
log(item.toString());
if (!item.isFormField()) {
String name = item.getName();
logger("上传的文件名 = " + name);
try {
item.write(new File(uploadPath + name));
} catch (Exception ex) {
logger(ex.getMessage());
}
}
}
} catch (FileUploadException ex1) {
logger("FileUploadException->" + ex1.getMessage());
}
}
// 建立文件夹路径
private boolean makeDir(String uploadPath) {
boolean isOK = false;
try {
File file = new File(uploadPath);
file.mkdirs();
isOK = true;
} catch (Exception e) {
isOK = false;
} finally {
return isOK;
}
}
// 建立文件夹路径
private boolean makeDirs(String uploadPath, String newDocStr) {
boolean isOK = false;
File file;
String[] temp;
try {
temp = newDocStr.split(",");
for (int i = 0; i < temp.length; i++) {
file = new File(uploadPath + temp[i] + "\\");
file.mkdirs();
}
isOK = true;
} catch (Exception e) {
isOK = false;
} finally {
return isOK;
}
}
}
Flex前台代码:
Actionscript代码
1.<?xml version="1.0" encoding="utf-8"?>
2.<mx:TitleWindow xmlns:fx="http://ns.adobe.com/mxml/2009"
3. xmlns:s="library://ns.adobe.com/flex/spark"
4. xmlns:mx="library://ns.adobe.com/flex/halo" layout="absolute" width="400" height="300"
5. creationComplete="CreationCompletedHandler()"
6. showCloseButton="true">
7. <fx:Script>
8. <![CDATA[
9. import mx.controls.Alert;
10. import mx.events.CloseEvent;
11. import mx.managers.PopUpManager;
12. import mx.utils.StringUtil;
13.
14. [Bindable]
15. private var _filename:String;
16.
17. public function get filename():String
18. {
19. return _filename;
20. }
21.
22. public function set filename(value:String):void
23. {
24. _filename = value;
25. }
26.
27.
28. [Bindable]
29. private var _file:FileReference=new FileReference();
30.
31. public function get file():FileReference
32. {
33. return _file;
34. }
35.
36. public function set file(value:FileReference):void
37. {
38. _file = value;
39. }
40.
41.
42. [Bindable]
43. private var _serveraddress:String;
44.
45. public function get serveraddress():String
46. {
47. return _serveraddress;
48. }
49.
50. public function set serveraddress(value:String):void
51. {
52. _serveraddress = value;
53. }
54.
55. /**creationComplete完成之后调用,获取服务器地址,建立事件监听
56. * @param null
57. * @author 陈文锋 54cwf@163.com
58. * @return void
59. * */
60. public function CreationCompletedHandler():void
61. {
62. Security.allowDomain("*");
63. var urlLoader:URLLoader=new URLLoader(new URLRequest("assets/conf/ServerAddressConfig.xml"));
64. urlLoader.addEventListener(Event.COMPLETE,CompletedHandler);
65. this.addEventListener(Event.CLOSE,TitleWindowClose);
66. file.addEventListener(ProgressEvent.PROGRESS,progressHandler);
67. file.addEventListener(Event.SELECT,selectedHandler);
68. file.addEventListener(IOErrorEvent.IO_ERROR,ioErrorHandler);
69. }
70.
71. private function ioErrorHandler(e:IOErrorEvent):void
72. {
73. Alert.show(e.toString());
74. }
75.
76. private function progressHandler(e:ProgressEvent):void
77. {
78. lblProgress.text = " 已上传 " + e.bytesLoaded
79. + " 字节,共 " + e.bytesTotal + " 字节";
80. var proc: uint = e.bytesLoaded / e.bytesTotal * 100;
81. uploadbar.setProgress(proc, 100);
82. uploadbar.label= "当前进度: " + " " + proc + "%";
83. }
84.
85. /**Event事件监听处理函数,弹出上传提示窗口
86. * @param e,Event类型事件参数
87. * @author 54cwf@163.com
88. * @return void
89. * */
90. private function selectedHandler(e:Event):void
91. {
92. Alert.show("上传 " + file.name + " (共 "+Math.round(file.size/1024)+"KB)?",
93. "确认上传",
94. Alert.YES|Alert.NO,
95. null,
96. proceedWithUpload);
97. }
98.
99. /**CloseEvent事件监听处理函数,访问upload的servlet服务
100. * @param e,Event类型事件参数
101. * @author 54cwf@163.com
102. * @return void
103. * */
104. private function proceedWithUpload(e:CloseEvent): void{
105. if (e.detail == Alert.YES)
106. {
107. filename=file.name;
108. var request:URLRequest = new URLRequest(StringUtil.trim(serveraddress));
109. try
110. {
111. file.upload(request);
112. }
113. catch (error:Error)
114. {
115. Alert.show("上传失败","错误");
116. }
117.
118. }
119. }
120.
121. private function upload(): void{
122. var typefiter:FileFilter=new FileFilter("Excel","*.xls");
123. file.browse([typefiter]);
124. }
125.
126. /**CloseEvent事件监听处理函数,关闭TitleWindow弹出窗口
127. * @param e,事件参数
128. * @author 54cwf@163.com
129. * @return void
130. * */
131. private function TitleWindowClose(e:CloseEvent):void
132. {
133. PopUpManager.removePopUp(this);
134. }
135.
136. /**Event事件监听处理函数,获取配置文件的文件上传路径
137. * @param e,事件参数
138. * @author 54cwf@163.com
139. * @return void
140. * */
141. private function CompletedHandler(e:Event):void
142. {
143. var configurationxml:XML=XML((URLLoader(e.target).data));
144. serveraddress=configurationxml.filesinservername;
145. }
146. ]]>
147. </fx:Script>
148. <mx:Canvas width="100%" height="100%">
149. <mx:VBox width="100%" horizontalAlign="center">
150. <mx:Label id="lblProgress" text="上传"/>
151. <mx:ProgressBar id="uploadbar" labelPlacement="bottom" themeColor="#F20D7A"
152. minimum="0" visible="true" maximum="100" label="当前进度: 0%"
153. direction="right" mode="manual" width="200"/>
154. <mx:Button label="上传文件" click="upload()"/>
155. </mx:VBox>
156. </mx:Canvas>
157.</mx:TitleWindow>
java Servlet 代码
Java代码
1.package com.yyhy.java.util;
2.
3.//多文件上传的Java端的类
4.import javax.servlet.http.HttpServlet;
5.import javax.servlet.http.HttpServletRequest;
6.import javax.servlet.http.HttpServletResponse;
7.import javax.servlet.ServletException;
8.import java.util.List;
9.import java.util.Iterator;
10.import java.io.File;
11.import java.io.IOException;
12.import java.io.UnsupportedEncodingException;
13.import java.net.URLDecoder;
14.import org.apache.commons.fileupload.FileUploadException;
15.import org.apache.commons.fileupload.disk.DiskFileItemFactory;
16.import org.apache.commons.fileupload.servlet.ServletFileUpload;
17.import org.apache.commons.fileupload.FileItem;
18.import org.apache.log4j.Logger;
19.import org.apache.commons.lang.ObjectUtils;
20.import org.springframework.context.ApplicationContext;
21.import org.springframework.context.support.ClassPathXmlApplicationContext;
22.
23.
24.public class FileUploadAction extends HttpServlet {
25.
26. // 限制文件的上传大小
27. private int maxPostSize = 100 * 1024 * 1024;
28. //文件上传地址
29. private String uploadPath;
30.
31. public FileUploadAction() {
32. //从配置文件中取得文件上传地址
33. setUploadPath();
34. }
35. public String getUploadPath() {
36. return uploadPath;
37. }
38. public void setUploadPath() {
39. //从配置文件中取得文件上传地址
40. ApplicationContext context = new ClassPathXmlApplicationContext("applicationContext.xml");
41. ServerAddress serverAddressBean=(ServerAddress)context.getBean("ServerAddressBean");
42. this.uploadPath = serverAddressBean.getUploadPath().trim();
43. }
44. // 文件上传
45. public void service(HttpServletRequest request, HttpServletResponse response)
46. throws ServletException
47. {
48. this.doUploadAdd(request, response);
49. }
50.
51. private void logger(String info) {
52. System.out.println(info);
53. }
54.
55. protected void doGet(HttpServletRequest request, HttpServletResponse response)
56. throws ServletException, IOException {
57. doUploadAdd(request, response);
58. }
59.
60. protected void doPost(HttpServletRequest request, HttpServletResponse response)
61. throws ServletException, IOException {
62. doUploadAdd(request, response);
63. }
64.
65. private void doUploadAdd(HttpServletRequest request,
66. HttpServletResponse response) throws ServletException {
67. logger("begin to upload");
68. try {
69. request.setCharacterEncoding("UTF-8");// 防止文件名称带有汉字后传到服务器乱码
70. //建立文件夹
71. this.makeDir(uploadPath);
72. } catch (UnsupportedEncodingException e) {
73. // TODO Auto-generated catch block
74. e.printStackTrace();
75. }
76. saveFiletoServer(request,response,uploadPath);
77. }
78.
79. private void doUploadDelete(HttpServletRequest request,HttpServletResponse response) throws ServletException
80. {
81. String dirtyStr = "";//需要删除的文件名(单个文件)或文件夹名列表
82. try
83. {
84. if (request.getParameter("dirtyStr") != null) {
85. dirtyStr=URLDecoder.decode(request.getParameter("dirtyStr"),"utf-8");//前台ENCODE,后台DECODE
86. logger("删除的文件(夹)为:" + dirtyStr);
87. }
88. }
89. catch (Exception e) {
90. // TODO Auto-generated catch block
91. logger(e.getMessage());
92. }
93.
94. try {
95. new DeleteFiles().DeleteModifyFiles(dirtyStr, uploadPath);
96. } catch (Exception e) {
97. logger(e.getMessage());
98. }
99. }
100. //保存文件到服务器中
101. private void saveFiletoServer(HttpServletRequest request,HttpServletResponse response,String uploadPath)
102. {
103. // 操作文件
104. response.setContentType("text/html; charset=UTF-8");
105. DiskFileItemFactory factory = new DiskFileItemFactory();
106. factory.setSizeThreshold(1024 * 4);
107. ServletFileUpload upload = new ServletFileUpload(factory);
108. upload.setFileSizeMax(maxPostSize);
109. logger("request========" + ObjectUtils.toString(request));
110. List fileItems = null;
111. try {
112. fileItems = upload.parseRequest(request);
113. logger("============" + ObjectUtils.toString(fileItems));
114. Iterator iter = fileItems.iterator();
115. while (iter.hasNext()) {
116. FileItem item = (FileItem) iter.next();
117. log(item.toString());
118. if (!item.isFormField()) {
119. String name = item.getName();
120. logger("上传的文件名 = " + name);
121. try {
122. item.write(new File(uploadPath + name));
123. } catch (Exception ex) {
124. logger(ex.getMessage());
125. }
126. }
127. }
128. } catch (FileUploadException ex1) {
129. logger("FileUploadException->" + ex1.getMessage());
130. }
131. }
132. // 建立文件夹路径
133. private boolean makeDir(String uploadPath) {
134. boolean isOK = false;
135. try {
136. File file = new File(uploadPath);
137. file.mkdirs();
138. isOK = true;
139. } catch (Exception e) {
140. isOK = false;
141. } finally {
142. return isOK;
143. }
144. }
145. // 建立文件夹路径
146. private boolean makeDirs(String uploadPath, String newDocStr) {
147. boolean isOK = false;
148. File file;
149. String[] temp;
150. try {
151. temp = newDocStr.split(",");
152. for (int i = 0; i < temp.length; i++) {
153. file = new File(uploadPath + temp[i] + "\\");
154. file.mkdirs();
155. }
156. isOK = true;
157. } catch (Exception e) {
158. isOK = false;
159. } finally {
160. return isOK;
161. }
162. }
163.}
package com.yyhy.java.util;
//多文件上传的Java端的类
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.ServletException;
import java.util.List;
import java.util.Iterator;
import java.io.File;
import java.io.IOException;
import java.io.UnsupportedEncodingException;
import java.net.URLDecoder;
import org.apache.commons.fileupload.FileUploadException;
import org.apache.commons.fileupload.disk.DiskFileItemFactory;
import org.apache.commons.fileupload.servlet.ServletFileUpload;
import org.apache.commons.fileupload.FileItem;
import org.apache.log4j.Logger;
import org.apache.commons.lang.ObjectUtils;
import org.springframework.context.ApplicationContext;
import org.springframework.context.support.ClassPathXmlApplicationContext;
public class FileUploadAction extends HttpServlet {
// 限制文件的上传大小
private int maxPostSize = 100 * 1024 * 1024;
//文件上传地址
private String uploadPath;
public FileUploadAction() {
//从配置文件中取得文件上传地址
setUploadPath();
}
public String getUploadPath() {
return uploadPath;
}
public void setUploadPath() {
//从配置文件中取得文件上传地址
ApplicationContext context = new ClassPathXmlApplicationContext("applicationContext.xml");
ServerAddress serverAddressBean=(ServerAddress)context.getBean("ServerAddressBean");
this.uploadPath = serverAddressBean.getUploadPath().trim();
}
// 文件上传
public void service(HttpServletRequest request, HttpServletResponse response)
throws ServletException
{
this.doUploadAdd(request, response);
}
private void logger(String info) {
System.out.println(info);
}
protected void doGet(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
doUploadAdd(request, response);
}
protected void doPost(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
doUploadAdd(request, response);
}
private void doUploadAdd(HttpServletRequest request,
HttpServletResponse response) throws ServletException {
logger("begin to upload");
try {
request.setCharacterEncoding("UTF-8");// 防止文件名称带有汉字后传到服务器乱码
//建立文件夹
this.makeDir(uploadPath);
} catch (UnsupportedEncodingException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
saveFiletoServer(request,response,uploadPath);
}
private void doUploadDelete(HttpServletRequest request,HttpServletResponse response) throws ServletException
{
String dirtyStr = "";//需要删除的文件名(单个文件)或文件夹名列表
try
{
if (request.getParameter("dirtyStr") != null) {
dirtyStr=URLDecoder.decode(request.getParameter("dirtyStr"),"utf-8");//前台ENCODE,后台DECODE
logger("删除的文件(夹)为:" + dirtyStr);
}
}
catch (Exception e) {
// TODO Auto-generated catch block
logger(e.getMessage());
}
try {
new DeleteFiles().DeleteModifyFiles(dirtyStr, uploadPath);
} catch (Exception e) {
logger(e.getMessage());
}
}
//保存文件到服务器中
private void saveFiletoServer(HttpServletRequest request,HttpServletResponse response,String uploadPath)
{
// 操作文件
response.setContentType("text/html; charset=UTF-8");
DiskFileItemFactory factory = new DiskFileItemFactory();
factory.setSizeThreshold(1024 * 4);
ServletFileUpload upload = new ServletFileUpload(factory);
upload.setFileSizeMax(maxPostSize);
logger("request========" + ObjectUtils.toString(request));
List fileItems = null;
try {
fileItems = upload.parseRequest(request);
logger("============" + ObjectUtils.toString(fileItems));
Iterator iter = fileItems.iterator();
while (iter.hasNext()) {
FileItem item = (FileItem) iter.next();
log(item.toString());
if (!item.isFormField()) {
String name = item.getName();
logger("上传的文件名 = " + name);
try {
item.write(new File(uploadPath + name));
} catch (Exception ex) {
logger(ex.getMessage());
}
}
}
} catch (FileUploadException ex1) {
logger("FileUploadException->" + ex1.getMessage());
}
}
// 建立文件夹路径
private boolean makeDir(String uploadPath) {
boolean isOK = false;
try {
File file = new File(uploadPath);
file.mkdirs();
isOK = true;
} catch (Exception e) {
isOK = false;
} finally {
return isOK;
}
}
// 建立文件夹路径
private boolean makeDirs(String uploadPath, String newDocStr) {
boolean isOK = false;
File file;
String[] temp;
try {
temp = newDocStr.split(",");
for (int i = 0; i < temp.length; i++) {
file = new File(uploadPath + temp[i] + "\\");
file.mkdirs();
}
isOK = true;
} catch (Exception e) {
isOK = false;
} finally {
return isOK;
}
}
}
Flex前台代码:
Actionscript代码
1.<?xml version="1.0" encoding="utf-8"?>
2.<mx:TitleWindow xmlns:fx="http://ns.adobe.com/mxml/2009"
3. xmlns:s="library://ns.adobe.com/flex/spark"
4. xmlns:mx="library://ns.adobe.com/flex/halo" layout="absolute" width="400" height="300"
5. creationComplete="CreationCompletedHandler()"
6. showCloseButton="true">
7. <fx:Script>
8. <![CDATA[
9. import mx.controls.Alert;
10. import mx.events.CloseEvent;
11. import mx.managers.PopUpManager;
12. import mx.utils.StringUtil;
13.
14. [Bindable]
15. private var _filename:String;
16.
17. public function get filename():String
18. {
19. return _filename;
20. }
21.
22. public function set filename(value:String):void
23. {
24. _filename = value;
25. }
26.
27.
28. [Bindable]
29. private var _file:FileReference=new FileReference();
30.
31. public function get file():FileReference
32. {
33. return _file;
34. }
35.
36. public function set file(value:FileReference):void
37. {
38. _file = value;
39. }
40.
41.
42. [Bindable]
43. private var _serveraddress:String;
44.
45. public function get serveraddress():String
46. {
47. return _serveraddress;
48. }
49.
50. public function set serveraddress(value:String):void
51. {
52. _serveraddress = value;
53. }
54.
55. /**creationComplete完成之后调用,获取服务器地址,建立事件监听
56. * @param null
57. * @author 陈文锋 54cwf@163.com
58. * @return void
59. * */
60. public function CreationCompletedHandler():void
61. {
62. Security.allowDomain("*");
63. var urlLoader:URLLoader=new URLLoader(new URLRequest("assets/conf/ServerAddressConfig.xml"));
64. urlLoader.addEventListener(Event.COMPLETE,CompletedHandler);
65. this.addEventListener(Event.CLOSE,TitleWindowClose);
66. file.addEventListener(ProgressEvent.PROGRESS,progressHandler);
67. file.addEventListener(Event.SELECT,selectedHandler);
68. file.addEventListener(IOErrorEvent.IO_ERROR,ioErrorHandler);
69. }
70.
71. private function ioErrorHandler(e:IOErrorEvent):void
72. {
73. Alert.show(e.toString());
74. }
75.
76. private function progressHandler(e:ProgressEvent):void
77. {
78. lblProgress.text = " 已上传 " + e.bytesLoaded
79. + " 字节,共 " + e.bytesTotal + " 字节";
80. var proc: uint = e.bytesLoaded / e.bytesTotal * 100;
81. uploadbar.setProgress(proc, 100);
82. uploadbar.label= "当前进度: " + " " + proc + "%";
83. }
84.
85. /**Event事件监听处理函数,弹出上传提示窗口
86. * @param e,Event类型事件参数
87. * @author 54cwf@163.com
88. * @return void
89. * */
90. private function selectedHandler(e:Event):void
91. {
92. Alert.show("上传 " + file.name + " (共 "+Math.round(file.size/1024)+"KB)?",
93. "确认上传",
94. Alert.YES|Alert.NO,
95. null,
96. proceedWithUpload);
97. }
98.
99. /**CloseEvent事件监听处理函数,访问upload的servlet服务
100. * @param e,Event类型事件参数
101. * @author 54cwf@163.com
102. * @return void
103. * */
104. private function proceedWithUpload(e:CloseEvent): void{
105. if (e.detail == Alert.YES)
106. {
107. filename=file.name;
108. var request:URLRequest = new URLRequest(StringUtil.trim(serveraddress));
109. try
110. {
111. file.upload(request);
112. }
113. catch (error:Error)
114. {
115. Alert.show("上传失败","错误");
116. }
117.
118. }
119. }
120.
121. private function upload(): void{
122. var typefiter:FileFilter=new FileFilter("Excel","*.xls");
123. file.browse([typefiter]);
124. }
125.
126. /**CloseEvent事件监听处理函数,关闭TitleWindow弹出窗口
127. * @param e,事件参数
128. * @author 54cwf@163.com
129. * @return void
130. * */
131. private function TitleWindowClose(e:CloseEvent):void
132. {
133. PopUpManager.removePopUp(this);
134. }
135.
136. /**Event事件监听处理函数,获取配置文件的文件上传路径
137. * @param e,事件参数
138. * @author 54cwf@163.com
139. * @return void
140. * */
141. private function CompletedHandler(e:Event):void
142. {
143. var configurationxml:XML=XML((URLLoader(e.target).data));
144. serveraddress=configurationxml.filesinservername;
145. }
146. ]]>
147. </fx:Script>
148. <mx:Canvas width="100%" height="100%">
149. <mx:VBox width="100%" horizontalAlign="center">
150. <mx:Label id="lblProgress" text="上传"/>
151. <mx:ProgressBar id="uploadbar" labelPlacement="bottom" themeColor="#F20D7A"
152. minimum="0" visible="true" maximum="100" label="当前进度: 0%"
153. direction="right" mode="manual" width="200"/>
154. <mx:Button label="上传文件" click="upload()"/>
155. </mx:VBox>
156. </mx:Canvas>
157.</mx:TitleWindow>
发表评论
-
Flex中如何去掉Tree控件默认文件夹图标、叶子节点图标
2011-11-01 16:07 1206利用folderClosedIcon和folderOpenIc ... -
Flex DataGrid数据的多种显示方式
2011-09-28 10:54 1450Flex DataGrid单元格显示数据有多种方式。 1.默认 ... -
Flex分页(适用于小型数据)
2011-09-27 15:53 992<?xml version="1.0" ... -
四种方式实现Flex页面跳转
2011-09-26 15:08 1059Flex页面跳转是不被大多数人知道的东西,这里向大家简单介绍一 ... -
Flex各种有用法小总结
2011-09-05 15:42 1024//获得屏幕的分辨率 var x:Number=Capabi ... -
Flex学习网址
2011-09-05 15:40 9601.国外站点 http://www.blogjava.net/ ... -
DataGrid删除数据后如何自动更新
2011-08-23 23:07 1355mainl.mxml <?xml version=&qu ... -
Flex学习站点汇总
2011-08-05 13:04 793一、国外站点 1.资源类 Adobe Flex 2 Com ...
相关推荐
综上所述,"flex+java文件上传"涉及到前端的Flex界面设计与交互、Flash Player运行环境、后端的Java处理逻辑以及文件上传的安全性和性能优化等多个知识点。在实际应用中,开发者需要结合这些技术来实现稳定、安全且...
在本文中,我们将深入探讨如何实现Flex与Java Servlet结合进行文件上传。首先,我们需要了解Flex是一种基于Adobe AIR的开源框架,用于构建富互联网应用程序(RIA),而Java Servlet是Java平台上的一个标准,用于处理...
本示例“flex+java文件上传完整实例”提供了一个完善的解决方案,它结合了Adobe Flex前端技术和Java后端技术,实现了用户友好的文件上传功能。Flex是一种开源的RIA(富互联网应用)开发框架,而Java则提供了强大的...
综上所述,Flex3和Java文件上传涉及前端的用户交互和后端的数据处理,需要理解Flex的ActionScript3编程、文件上传机制以及Java Web服务的实现。同时,安全性、性能和用户体验也是设计此类系统时必须考虑的重要因素。
Flex+Java Servlet处理文件上传 关于上传文件
本文将深入探讨“flex_java文件上传(一)”这一主题,主要关注如何使用Flex与Java结合实现文件上传功能。Flex是一种用于创建富互联网应用程序(RIA)的开源框架,而Java则是一种广泛使用的后端开发语言。我们将围绕...
在提供的压缩包“flex3+java文件上传”中,可能包含了一个完整的示例项目,包括Flex的源代码、Java的Servlet代码以及必要的配置文件。导入这个项目后,可以直接运行并测试文件上传功能,这对于学习和理解Flex3与Java...
总结起来,本示例介绍了如何使用Flex客户端与Java服务器配合实现文件上传功能。在Flex中,通过FileReference类选择和上传文件;在Java端,使用Spring MVC的MultipartFile接口接收并处理上传的文件。这个过程涉及到...
在"PhotoUpload"这个压缩包文件中,很可能包含了Flex项目的源代码(可能包括.mxml和.as文件)以及Java后端的源代码(可能是.java文件)。解压后,开发者可以研究和学习如何在Flex中创建文件选择控件,如何监听和触发...
**标签** "Flex Java 文件上传" 暗示了此压缩包可能包含的代码示例或教程,涵盖了Flex前端与Java后端之间的通信,以及处理文件操作的相关代码。文件名列表未给出完整信息,但通常可能包括ActionScript类文件(如`.as...
Flex+Java、PHP 批量上传实例文档Flex+Java、PHP 批量上传实例文档Flex+Java、PHP 批量上传实例文档Flex+Java、PHP 批量上传实例文档Flex+Java、PHP 批量上传实例文档Flex+Java、PHP 批量上传实例文档Flex+Java、...
Flex 文件上传技术是一种在Web应用中实现用户向服务器端上传文件的方法,通常涉及到前端的Flex技术与后端的Java服务进行交互。Flex是一款强大的富互联网应用程序(RIA)开发框架,由Adobe公司提供,用于创建动态、...
标题中的“Flex+Java多文件上传”指的是使用Adobe Flex(一种富互联网应用程序开发框架)与Java技术相结合,实现用户在Web应用中上传多个文件的功能。这个功能通常涉及到前端的用户界面设计、后端的文件处理逻辑以及...
【标签】"源码"意味着这个压缩包中可能包含完整的源代码,这对于学习和理解Flex与Java Servlet整合的文件上传机制非常有帮助。"工具"可能指的是该压缩包中可能包含的辅助工具,如构建脚本或者IDE配置文件,帮助...
综上所述,这个项目提供了一套完整的解决方案,涵盖了从Flex前端的文件选择、大小限制、进度显示,到Java后端的文件接收、大小检查和存储等全部流程,是学习和实践Flex与Java集成开发文件上传功能的一个良好示例。
在Flex中实现多文件上传,通常涉及到ActionScript编程、组件使用以及与服务器端的交互。下面将详细介绍如何使用Flex来实现这个功能。 一、Flex中的文件选择组件 在Flex中,我们可以使用`FileReference`类来处理文件...
在文件上传场景中,BlazeDS作为Flex与Java之间的通讯中间件,负责将Flex客户端发送的文件数据转发给Java服务端,并将服务端的响应回传给Flex。 4. **文件上传实现**: - **前端**:在Flex应用中,用户可以选择或...