上传参数:httpservice封装了 urlrequest
上传文件:所有上传都是用POST Content type为:multipart/form-data (如同html表单的设置一样)
var request:URLRequest=new URLRequest("http://localhost:8080/webproject12/servlet/upload");
myFileRef.upload(request);
可以加一个filter class 当提交成功时候 绑定一个变量到session
filter过滤所有要访问JSP生成XML的请求 如果session没有这个变量 拒绝访问(方式根据链接访问JSP)
提交文件用import flash.net.FileReference;
MXML部分:
<?xml version="1.0" encoding="utf-8"?>
<mx:Application xmlns:mx="http://www.adobe.com/2006/mxml" layout="horizontal">
<mx:Script>
<![CDATA[
/**
* 一个HttpService 与servlet通信的例子
* 发送文件 和上传表单 先文件上传成功后继续传送表单
* 发送文件的成功由事件监听
* 发送表单后会返回由JSP生成的动态XML文件
* */
import mx.rpc.events.FaultEvent;
import mx.rpc.events.ResultEvent;
import flash.net.URLRequest;
import flash.net.FileReference;
import flash.events.Event;
import flash.events.IOErrorEvent;
private var myFileRef:FileReference=null ;
private var request:URLRequest=null;
private function doFileBrowse():void{//点击浏览文件选项
myFileRef = new FileReference();
myFileRef.addEventListener(Event.SELECT,doSelect);
myFileRef.browse();
}
private function doSelect(evt:Event):void{//为文件文本框赋值
imageName.text=myFileRef.name.toString();
}
private function doUpForm():void{//点击最后提交按钮
request=new URLRequest("http://localhost:8080/webproject12/servlet/upload");
myFileRef.upload(request); //图片文件的提交
myFileRef.addEventListener(IOErrorEvent.IO_ERROR,errorHandler);//文件失败上传监听事件
myFileRef.addEventListener(Event.COMPLETE,doFileUploadComplete);//文件成功上传监听事件
}
private function errorHandler(evt:IOErrorEvent):void{
trace("上传失败,检查网络");
}
private function doFileUploadComplete(evt:Event):void{
trace("文件上传成功 继续传送表单");
up.send();//继续提交文字表单
}
private function doResult(event:ResultEvent):void{
trace(event.result);
}
private function doFault(event:FaultEvent):void{
trace("表单发送失败");
}
]]>
</mx:Script>
<mx:HTTPService id="up" url="http://localhost:8080/webproject12/flextest"
result="doResult(event)" fault="doFault(event)"
method="POST" resultFormat="xml" >
<mx:request xmlns="">
<username>
{username.text}
</username>
<imageName>
{imageName.text}
</imageName>
</mx:request>
</mx:HTTPService>
<mx:VBox height="100%" width="100%">
<mx:Form>
<mx:FormHeading label=" test load"/>
<mx:FormItem label=" username:">
<mx:TextInput id="username"/>
</mx:FormItem>
<mx:FormItem label="Image Name" direction="horizontal">
<mx:TextInput id="imageName" editable="false"/>
<mx:Button click="doFileBrowse()" label="Browse"/>
</mx:FormItem>
<mx:FormItem>
<mx:Button label="提交" click="doUpForm()"/>
</mx:FormItem>
</mx:Form>
</mx:VBox>
</mx:Application>
servlet部分:
upload。java 不需要回馈 文件接收器
1.
要设置好初始化参数 给与一个上传附件的路径
通过:
private ServletContext sc =config.getServletContext();
sc.getRealPath("/");得到应用真是根目录
private String savePath = config.getInitParameter("savePath");// 保存文件夹
sc.getRealPath("/")+savePath 是保存目录
2.
用了COMMONS FILEUPLOAD组件 和commons IO 组件
package org.zizi.servlet;
import java.io.File;
import java.io.IOException;
import java.io.PrintWriter;
import java.util.Iterator;
import java.util.List;
import javax.servlet.ServletConfig;
import javax.servlet.ServletContext;
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;
public class UploadServelt extends HttpServlet {
private static final long serialVersionUID = -850828778548588525L;
private ServletContext sc;// application 上传组件要用
private String savePath;// 保存路径
public void doGet(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
doPost(request, response);
}
public void doPost(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
request.setCharacterEncoding("utf-8");
// 开始组建的使用
DiskFileItemFactory factory = new DiskFileItemFactory();
ServletFileUpload upload = new ServletFileUpload(factory);
try {
List list = upload.parseRequest(request);// 解析传过来的内容 返回LIST
Iterator it = list.iterator();// 对LIST进行枚举
while (it.hasNext()) {
FileItem item = (FileItem) it.next();
// 判断是文本信息还是对象(文件)
if (item.isFormField()) {
// 如果是文本信息返回TRUE
System.out.println("参数" + item.getFieldName() + ":"
+ item.getString("UTF-8"));
// 注意输出值的时候要注意加上编码
} else {
if (item.getName() != null && !item.getName().equals("")) {
System.out.println("上传文件的大小:" + item.getSize());
System.out.println("上传文件的类型:" + item.getContentType());
System.out.println("上传文件的名称:" + item.getName());
System.out.println(sc.getRealPath("/") + savePath);
// 保存在服务器硬盘中
File tempFile = new File(item.getName());// 临时FILE对象
// 此时有路径的名字
// TEMPFILE主要为了获取文件的单纯文件名
File file = new File(sc.getRealPath("/") + savePath,
"kdj"+(tempFile.getName()).substring((tempFile.getName()).length()-4,(tempFile.getName()).length()));
//在这里可以更改名字
//用subString 的方法截取后缀 就可以加上自定义名称放在第二个参数
// 这个FILE是真正要保存的文件
item.write(file);// 写入服务器
// 返回结果
request.setAttribute("upload.message", "上传成功");
} else {
request.setAttribute("upload.message", "没有选择上传文件");
}
}
}
} catch (FileUploadException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (Exception e) {
// TODO Auto-generated catch block
e.printStackTrace();
request.setAttribute("upload.message", "上传没成功");
}
request.getRequestDispatcher("/uploadResult.jsp").forward(request, response);
}
public void init(ServletConfig config) {
//实现初始化文件 获取初始化参数 路径 和获取 一个全局服务器对象 备用
savePath = config.getInitParameter("savePath");// 初始化绑定参数 表明保存在哪
sc = config.getServletContext();
}
}
接收表单的servlet:flextest。java
package org.zizi.test;
import java.io.IOException;
import java.io.PrintWriter;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
public class FLEXTest extends HttpServlet {
private static final long serialVersionUID = -154781975203117748L;
public void doGet(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
}
public void doPost(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
response.setContentType("text/html;charset=utf-8");
request.setCharacterEncoding("utf-8");
String n=request.getParameter("username");
String m=request.getParameter("imageName");
request.setAttribute("pupload.message1", n);
request.setAttribute("pupload.message2", m);
request.getRequestDispatcher("/uploadResult2.jsp").forward(request, response);
//FLEX会接收 这个转向的JSP页面动态生成的XML文件
}
}
web。xml
<servlet>
<servlet-name>UploadServelt</servlet-name>
<servlet-class>org.zizi.servlet.UploadServelt</servlet-class>
<init-param>
<param-name>savePath</param-name>
<param-value>uploads</param-value>
</init-param>
</servlet>
<servlet>
<servlet-name>SendMailServlet</servlet-name>
<servlet-class>org.zizi.sendMail.SendMailServlet</servlet-class>
</servlet>
uploadResult2.jsp
<%@page language="java" contentType="text/xml;charset=utf-8" pageEncoding="UTF-8"%><?xml version="1.0" encoding="utf-8"?>
<cat>
<dog name="${requestScope['pupload.message2']}">
</dog>
<dog name="${requestScope['pupload.message1']}">
</dog>
</cat>
结果:
servlet 输出:
参数Filename:安博之泪.jpg
上传文件的大小:124849
上传文件的类型:application/octet-stream
上传文件的名称:安博之泪.jpg
E:\tomcat6\webapps\webproject12\uploads
参数Upload:Submit Query
flex 输出:
[SWF] E:\workspaceforFlex\forwritingshop\bin-debug\test.swf - 926,895 bytes after decompression
文件上传成功 继续传送表单
<cat><dog name="39254E3A-CC97-4FFE-8051-D152BF2A9E1F.jpg" /><dog name="zizi" /></cat>
总结,完全可以全部传送去一个SERVLET----UPLOAD,但是需要保存request的参数 可以建一个HashMap<String,String>(),然后保存参数。备以后存入数据库使用。
但是,需要调用两次servlet。。。。因为Httpservice的contenttype没有MULtiple/form-data。。。。??