以下是通过选择本地图片文件,然后显示预览,
通过将图片转化为byteArray再传递给Webservices进行上传
C#代码(Webservices):
[WebMethod(Description = "Web 服务提供的方法,返回是否文件上载成功与否。")]
[System.Xml.Serialization.XmlInclude(typeof(Picture))]
public bool UploadFiles(Pictures files)
{
try
{
foreach (Picture p in files.ps)
{
///定义并实例化一个内存流,以存放提交上来的字节数组。
MemoryStream m = new MemoryStream(p.fs);
FileStream f = new FileStream(Server.MapPath(".") + "\\"
+ p.filename, FileMode.Create);
m.WriteTo(f);
m.Close();
f.Close();
f = null;
m = null;
}
return true;
}
catch
{
return false;
}
}
Pictures是Picture的数组集合对象,也可以将Pictures换成Picture[],生成flex中通过自动生成Webservices中间代码实现
Picture对象:
public class Picture
{
public Picture()
{
//
// TODO: 在此处添加构造函数逻辑
//
}
public byte[] fs;
public string filename;
}
Flex上传的代码:
private var pis:ArrayOfPicture=new ArrayOfPicture();
private var s:Service;
private function init():void
{
s=new Service();
ExternalInterface.addCallback("OnFileChange",frSelectHandler);//注册JS回调
btnBrowser.addEventListener(MouseEvent.CLICK,mouseClickHandler);
}
private function mouseClickHandler(event:MouseEvent):void
{
ExternalInterface.call("Browser");//调用JS中Browser函数
}
private var i:Number=0;
private function frSelectHandler(path:String):void
{
var img:MyImage=new MyImage();
img.name="img"+i;
img.source = path;
img.test=path;
imgbox.addChild(img);
i++;
}
private function uploadimgs():void{
pis.removeAll();
for(var i:Number=0;i<imgbox.getChildren().length;i++){
var img:MyImage=imgbox.getChildByName("img"+i) as MyImage;
var ohSnap:ImageSnapshot = ImageSnapshot.captureImage((imgbox.getChildByName("img"+i) as MyImage));
var str:String=ImageSnapshot.encodeImageAsBase64(ohSnap);
var b64:Base64Decoder=new Base64Decoder();
b64.decode(str);
var p:Picture=new Picture();
p.fs=b64.toByteArray();
p.filename=int(Math.random()*100000000)+img.test.substring(img.test.length-4,img.test.length);
pis.addPicture(p);
}
s.adduploadFilesEventListener(upload);
var ps:Pictures=new Pictures();
ps.ps=pis;
s.uploadFiles(ps);
}
private function upload(e:UploadFilesResultEvent):void{
if(e.result){
Alert.show("上传成功!");
}
}
标签部分:
<mx:Button x="55" id="btnBrowser" y="50" label="选择文件"/>
<mx:VBox id="imgbox" x="188.5" y="10" verticalScrollPolicy="auto">
</mx:VBox>
<mx:Button x="55" y="184" label="上传(多个)" click="uploadimgs()"/>
在网页中添加以下代码:
<script language="JavaScript" type="text/javascript">
var requiredMajorVersion = 9;
var requiredMinorVersion = 0;
var requiredRevision = 28;
//关键代码
function Browser()
{
document.getElementById("fileInput").click();
}
function OnFileChange()
{
//TestUpfile是flash名称
thisMovie("TestUpfile").OnFileChange(document.getElementById("fileInput").value);
}
function thisMovie(movieName) {
if (navigator.appName.indexOf("Microsoft") != -1) {
return window[movieName];
} else {
return document[movieName];
}
}
</script>
添加文件标签:<input type="file" id="fileInput" style="display:none" οnchange="OnFileChange()" />