Flex上传图片等信息到数据库,并下载显示图片

1.上传到SqlServer
功能为上传漫画至SqlServer,先上传非二进制图片信息(漫画编号,卷数,本卷图片编号),上传成功后根据返回的自增
主键再上传二进制图片.
采用FluorineFx调用RemoteObject操作数据库,上传图片则采用FileReference上传到UploadManHua.ashx

C#端远程服务类
ManHuaService.cs

Code
<!--

Code highlighting produced by Actipro CodeHighlighter (freeware)
http://www.CodeHighlighter.com/

-->using System;
using System.Collections.Generic;
using System.Text;
using System.Data;
using System.Data.SqlClient;
using FluorineFx;
using FluorineFx.AMF3;

namespace ServiceLibrary
{
    [RemotingService(
"man hua service")]
    
public class ManHuaService
    {
        [DataTableType(
"ServiceLibrary.ManHuaTuPian")]
        
/// <summary>
        
/// 获得一张漫画图片
        
/// </summary>
        
/// <param name="ManHuaID">漫画编号</param>
        
/// <param name="JuanShu">卷数</param>
        
/// <param name="BenJuanTuPianXH">图片顺序号</param>
        
/// <returns></returns>
        public ManHuaTuPian GetOneManHuaTuPian(int ManHuaID, int JuanShu, int BenJuanTuPianXH)
        {
            SqlConnection con 
= new SqlConnection("server=.;uid=sa;pwd=;database=ManHuaLiuLan");
            con.Open();
            SqlCommand cmd 
= new SqlCommand("select * from ManHuaTuPian where ManHuaID=" + ManHuaID.ToString() + " and JuanShu=" + JuanShu.ToString() + " and BenJuanTuPianXH=" + BenJuanTuPianXH.ToString(), con);
            SqlDataAdapter dap 
= new SqlDataAdapter(cmd);
            DataTable tb 
= new DataTable();
            dap.Fill(tb);
            con.Close();
            
if (tb.Rows.Count > 0)
            {
                ManHuaTuPian objManHua 
= new ManHuaTuPian();
                objManHua.ID 
= int.Parse(tb.Rows[0]["ID"].ToString());
                objManHua.ManHuaID 
= int.Parse(tb.Rows[0]["ManHuaID"].ToString());
                objManHua.JuanShu 
= int.Parse(tb.Rows[0]["JuanShu"].ToString());
                objManHua.BenJuanTuPianXH 
= int.Parse(tb.Rows[0]["BenJuanTuPianXH"].ToString());
                
byte[] bytes = (byte[])tb.Rows[0]["TuPian"];
                ByteArray imagebytes 
= new ByteArray();
                imagebytes.WriteBytes(bytes,
0,bytes.Length);
                objManHua.TuPian 
= imagebytes;
                
return objManHua;
            }
            
else
                
return null;
        }

        
/// <summary>
        
/// 插入一张漫画图片
        
/// </summary>
        
/// <param name="ManHuaID">漫画编号</param>
        
/// <param name="JuanShu">卷数</param>
        
/// <param name="BenJuanTuPianXH">本卷图片序号</param>
        
/// <returns>插入成功记录的自增主键</returns>
        public int InsertManHua(int ManHuaID,int JuanShu,int BenJuanTuPianXH)
        {
            SqlConnection con 
= new SqlConnection("server=.;uid=sa;pwd=;database=ManHuaLiuLan");
            con.Open();
            SqlCommand cmd 
= new SqlCommand();
            cmd.Connection 
= con;
            cmd.CommandText 
= "insert into ManHuaTuPian(ManHuaID,JuanShu,BenJuanTuPianXH) values(@ManHuaID,@JuanShu,@BenJuanTuPianXH)\r\nselect scope_identity()";
            SqlParameterCollection sqlParams 
= cmd.Parameters;
            sqlParams.Add(
"@ManHuaID", SqlDbType.Int);
            sqlParams.Add(
"@JuanShu", SqlDbType.Int);
            sqlParams.Add(
"@BenJuanTuPianXH", SqlDbType.Int);
            sqlParams[
0].Value = ManHuaID;
            sqlParams[
1].Value = JuanShu;
            sqlParams[
2].Value = BenJuanTuPianXH;
            
int identityID;
            identityID 
= int.Parse(cmd.ExecuteNonQuery().ToString());
            con.Close();
            con.Dispose();
            
return identityID;
        }

        
/// <summary>
        
/// 更新漫画图片
        
/// </summary>
        
/// <param name="ID">漫画图片编号</param>
        
/// <param name="imagebytes">二进制图片字节数组</param>
        
/// <returns>成功返回true,失败返回false.</returns>
        public void UpdateManHuaTuPian(int ID, byte[] imagebytes)
        {
            SqlConnection con 
= new SqlConnection("server=.;uid=sa;pwd=;database=ManHuaLiuLan");
            con.Open();
            SqlCommand cmd 
= new SqlCommand("update ManHuaTuPian set TuPian=@TuPian where ID=@ID", con);
            cmd.Parameters.Add(
new SqlParameter("@TuPian", imagebytes));
            cmd.Parameters.Add(
new SqlParameter("@ID", ID));
            cmd.ExecuteNonQuery();
            con.Close();
            con.Dispose();
        }
    }

}


1.上传二进制和其它信息到数据库

上传界面
UploadManHua.mxml:

Code
<!--

Code highlighting produced by Actipro CodeHighlighter (freeware)
http://www.CodeHighlighter.com/

--><?xml version="1.0" encoding="utf-8"?>
<mx:Application xmlns:mx="http://www.adobe.com/2006/mxml" layout="absolute" fontSize="12">
    
<mx:RemoteObject id="ManHuaService" destination="fluorine" source="ServiceLibrary.ManHuaService">
        
<mx:method name="InsertManHua" result="InsertManHua_onResult(event)" fault="InsertManHua_onFault(event)">
        
</mx:method>
    
</mx:RemoteObject>
    
<mx:Script>
        
<![CDATA[
            import mx.rpc.events.FaultEvent;
            import mx.rpc.events.ResultEvent;
            import mx.controls.Alert;
            private var fileRef:FileReference = new FileReference();
            private function insertManHua(evt:MouseEvent):void
            {
                ManHuaService.InsertManHua(int(txtManHuaID.text),int(txtJuanShu.text),int(txtBenJuanTuPianXH.text));
            }
            private function InsertManHua_onResult(evt:ResultEvent):void
            {
                var identityID:int = int(evt.result);
                lblIdentityID.text = identityID.toString();
            }
            private function InsertManHua_onFault(evt:FaultEvent):void
            {
                Alert.show("插入失败!");
            }
            private function pickfile():void{
                 var imageTypes:FileFilter = new FileFilter("图片 (*.jpg, *.jpeg)", "*.jpg;*.jpeg;");
                 var allTypes:Array = new Array(imageTypes);
                 fileRef.addEventListener(Event.SELECT, selectHandler);
                 fileRef.addEventListener(Event.COMPLETE, completeHandler);
                 fileRef.addEventListener(IOErrorEvent.IO_ERROR,ioerrorHandler);
                 fileRef.addEventListener(ProgressEvent.PROGRESS, progressHandler);
                 fileRef.addEventListener("ioError", ioerrorHandler);
                 try{
                     var success:Boolean = fileRef.browse(allTypes);
                 }catch (error:Error){
                     trace("Unable to browse for files."+error.toString());
                 }
             }
             
             private function ioerrorHandler(event:Event):void{
                 trace("Unable to upload file."+event.toString());
             }
             private function progressHandler(event:ProgressEvent):void{
                 lblText.text = " 已上传 " + (event.bytesLoaded/1024).toFixed(2)+ " K,共 " + (event.bytesTotal/1024).toFixed(2) + " K";
                var proc: uint = event.bytesLoaded / event.bytesTotal * 100;
                lbProgress.setProgress(proc, 100);
                lbProgress.label= "当前进度: " + " " + proc + "%";
             
             }
             private function selectHandler(event:Event):void{
                txtPath.text = fileRef.name;
             }
             private function completeHandler(event:Event):void{
                 Alert.show("上传成功");
             }
             
             private function upload(evt:MouseEvent):void
             {
                 var request:URLRequest = new URLRequest("http://localhost:8012/UploadManHua.ashx");
                 var variables:URLVariables = new URLVariables();
                 variables.ID = int(lblIdentityID.text);
                 request.data = variables;
                try
                {
                    fileRef.upload(request);
                }
                catch (error:Error)
                {
                    trace("Unable to upload file."+error.toString());
                }
             }
        
]]>
    
</mx:Script>
    
<mx:Label x="44" y="10" text="漫画ID:" fontSize="12"/>
    
<mx:TextInput x="107" y="10" id="txtManHuaID" text="1"/>
    
<mx:Label x="58" y="40" text="卷数:" fontSize="12"/>
    
<mx:TextInput x="107" y="40" id="txtJuanShu" text="1"/>
    
<mx:Label x="10" y="70" text="本卷图片序号:" fontSize="12"/>
    
<mx:TextInput x="107" y="70" id="txtBenJuanTuPianXH"/>
    
<mx:Label x="58" y="138" text="图片:" fontSize="12"/>
    
<mx:TextInput x="107" y="134" id="txtPath"/>
    
<mx:Button x="275" y="134" label="浏览" fontSize="12" click="pickfile()"/>
    
<mx:Button x="335" y="134" label="上传" fontSize="12" click="upload(event)"/>
    
<mx:ProgressBar id="lbProgress" x="10" y="162" width="457" themeColor="#F20D7A" minimum="0" mode="manual" maximum="100" label="当前进度: 0%" styleName="myfont" fontWeight="normal"/>
    
<mx:Label id="lblText" x="10" y="198"/>
    
<mx:Button x="107" y="100" label="确认" fontSize="12" click="insertManHua(event)"/>
    
<mx:Label x="179.5" y="106" text="记录自增主键:" fontSize="12"/>
    
<mx:TextInput x="276.5" y="102" id="lblIdentityID" width="50.5"/>
</mx:Application>

 
用于上传C#的ashx,接收文件流,把文件流转换为字节数组byte[],传入ManHuaService进行上传到数据库中.
UploadManHua.ashx:

Code
<!--

Code highlighting produced by Actipro CodeHighlighter (freeware)
http://www.CodeHighlighter.com/

--><%@ WebHandler Language="C#" Class="UploadManHua" %>

using System;
using System.Web;
using System.Data.SqlClient;
using System.IO;

public class UploadManHua : IHttpHandler {

    
private string uploadFolder = "UpLoad";
    
public void ProcessRequest (HttpContext context) {
        context.Response.ContentType 
= "text/plain";
        
//上传文件至SqlServer
        HttpFileCollection files = context.Request.Files;
        
if (files.Count > 0)
        {
            
string path = context.Server.MapPath(uploadFolder);
            HttpPostedFile file 
= files[0];

            
if (file != null && file.ContentLength > 0)
            {
                
//string savePath = path + "/" + context.Request.Form["fileName"];
                
//file.SaveAs(savePath);
                
                Stream fs 
= file.InputStream;
                Byte[] imagebytes 
= new byte[fs.Length]; 
                BinaryReader br 
= new System.IO.BinaryReader(fs);
                imagebytes 
= br.ReadBytes(Convert.ToInt32(fs.Length));
                
string strID = context.Request.Params["ID"];
                
try
                {
                    
new ServiceLibrary.ManHuaService().UpdateManHuaTuPian(int.Parse(strID), imagebytes);               
                    context.Response.Write(
"成功");
                }
                
catch
                {
                    context.Response.Write(
"失败");
                }
            }
        }
        
else
        {
            context.Response.Write(
"参数错误");
            context.Response.End();
        }

    }
 
    
public bool IsReusable {
        
get {
            
return false;
        }
    }

}



2.读取SqlServer的二进制图片
C#端用FluorineFx.AMF3.ByteArray保存二进制对象,使用Flex端的ByteArray进行接收,并显示在图片中.图片使
用了网友的ByteArrayImage类(继承自mx.controls.Image).

C#端读取数据库记录,将读出的二进制由byte[]转换成ByteArray.

漫画图片实体类 ManHuaTuPian.cs

Code
<!--

Code highlighting produced by Actipro CodeHighlighter (freeware)
http://www.CodeHighlighter.com/

-->using System;
using System.Collections.Generic;
using System.Text;
using FluorineFx.AMF3;

namespace ServiceLibrary
{
    
public class ManHuaTuPian
    {
        
private int _ID;
        
private int _ManHuaID;
        
private int _JuanShu;
        
private int _BenJuanTuPianXH;
        
private ByteArray _TuPian;

        
public int ID
        {
            
set
            {
                
this._ID = value;
            }
            
get
            {
                
return this._ID;
            }
        }

        
public int ManHuaID
        {
            
set
            {
                
this._ManHuaID = value;
            }
            
get
            {
                
return this._ManHuaID;
            }
        }

        
public int JuanShu
        {
            
set
            {
                
this._JuanShu = value;
            }
            
get
            {
                
return this._JuanShu;
            }
        }

        
public int BenJuanTuPianXH
        {
            
set
            {
                
this._BenJuanTuPianXH = value;
            }
            
get
            {
                
return this._BenJuanTuPianXH;
            }
        }

        
public ByteArray TuPian
        {
            
set
            {
                
this._TuPian = value;
            }
            
get
            {
                
return this._TuPian;
            }
        }
    }
}


用于显示二进制图片的组件类 ByteArrayImage
ByteArrayImage.as

Code
<!--

Code highlighting produced by Actipro CodeHighlighter (freeware)
http://www.CodeHighlighter.com/

-->package customComp
{
    
import flash.display.Loader;
    
import flash.events.Event;
    
import flash.system.LoaderContext;
    
import flash.utils.ByteArray;
    
import mx.controls.Image;
    
    
public class ByteArrayImage extends mx.controls.Image
    {
        
private var _loader:Loader = new Loader();
        
public function Image():void {}
        override 
protected function createChildren():void
        {
            addChild(_loader);
        }
        
        
public function loadBytes(bytes:ByteArray,context:LoaderContext=null):void
        {
            _loader.loadBytes(bytes, context);
            _loader.contentLoaderInfo.addEventListener(Event.COMPLETE, onBytesLoaded);
        }
        
        
private function onBytesLoaded(e:Event):void
        {
            
this.width = e.target.width;
            
this.height = e.target.height;
        }
    }
}

 


调用显示二进制图片,这里使用ByteArrayImage

Code
<!--

Code highlighting produced by Actipro CodeHighlighter (freeware)
http://www.CodeHighlighter.com/

--><?xml version="1.0" encoding="utf-8"?>
<mx:Application xmlns:mx="http://www.adobe.com/2006/mxml" layout="absolute" xmlns:ns1="*" xmlns:ns2="customComp.*">
    
<mx:RemoteObject id="ManHuaService" destination="fluorine" source="ServiceLibrary.ManHuaService">
        
<mx:method name="GetOneManHuaTuPian" result="GetOneManHuaTuPian_onResult(event)">
        
</mx:method>
    
</mx:RemoteObject>
    
<mx:Script>
        
<![CDATA[
            import mx.messaging.AbstractConsumer;
            import customComp.ByteArrayImage;
            import mx.collections.ArrayCollection;
            import mx.rpc.events.ResultEvent;
            import mx.controls.Alert;
            internal function onClick(evt:MouseEvent):void{
                ManHuaService.GetOneManHuaTuPian(1,1,1);
            }
            internal function GetOneManHuaTuPian_onResult(evt:ResultEvent):void{
                var objManHuaTuPian:Object = evt.result;            
                var arrImage:ByteArray = new ByteArray();
                arrImage = objManHuaTuPian.TuPian;
                img.loadBytes(arrImage);                    
            }
        
]]>
    
</mx:Script>
    
<mx:Button x="10" y="10" label="Button" click="onClick(event)"/>
    
<ns2:ByteArrayImage x="220" y="40" id="img"/>
</mx:Application>

http://www.cnblogs.com/yuji/archive/2009/05/07/1452106.html

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值