平时做技术实践时,很多问题不是概念不会,而是细节没串起来。拿“flex利用webservice上传照片实现方法代码”来说,它看着像小点,放到项目里常会牵出环境、配置、兼容性和维护成本。下面按实际采用顺序,把思路、关键写法和容易踩坑的地方讲清楚,便于大家直接对照操作。
WebService端代码复制代码 代码如下所示:
///
/// 上传文件到远程服务器
///
/// 文件流
/// 文件名
///
[WebMethod(Description = "上传文件到远程服务器.")]
public string UploadFile(byte[] fileBytes, string fileName)
{
try
{
在这个场景下,MemoryStream memoryStream = new MemoryStream(fileBytes); //1.定义同时实例化一个内存流,以存放提交上来的字节数组。
理解这一步时,FileStream fileUpload = new FileStream(Server.MapPath(".") + "\\" + fileName, FileMode.Create); ///2.定义实际文件对象,保存上载的文件。
memoryStream.WriteTo(fileUpload); ///3.把内存流里的数据写入物理文件
memoryStream.Close();
fileUpload.Close();
fileUpload = null;
memoryStream = null;
return "文件已经上传成功";
}
catch (Exception ex)
{
return ex.Message;
}
}
Flex客户端代码
复制代码 代码如下所示:
xmlns:mx="library://ns.adobe.com/flex/mx" minWidth="955" minHeight="600" creationComplete="application1_creationCompleteHandler(event)">
import mx.controls.Alert;
import mx.events.FlexEvent;
import mx.graphics.codec.JPEGEncoder;
import mx.rpc.events.FaultEvent;
import mx.rpc.events.ResultEvent;
protected function application1_creationCompleteHandler(event:FlexEvent):void
{
var width :int = imgID.width;
var height :int = imgID.height;
var bitmapData:BitmapData =new BitmapData(width,height);
bitmapData.draw(imgID);
var byteArr:ByteArray = bitmapData.getPixels(new Rectangle(0,0,width,height));
var byteArr123:ByteArray =new JPEGEncoder().encodeByteArray(byteArr,width,height);
webService.UploadFile(byteArr123,"123.png");
}
protected function webService_faultHandler(event:FaultEvent):void
{
Alert.show(event.fault.toString());
}
protected function webService_successHandler(event:ResultEvent):void
{
Alert.show(event.result.toString());
}
]]>

