flex上传图片

flex上传图片需引用UploadPostHelper.as

 

protected function btnClick(event:MouseEvent):void
            {
                //要上传的图片
                var one4data:Bitmap= model.scanvo.currentScanImage;
                //图片转换成字符数组
                //对传送数据编码(很重要)
                var data:ByteArray=new JPGEncoder().encode(one4data.bitmapData);

               
                var url:String="http://www.test.com/upload/UploadAction.action";//上传地址自己根据实际情况定
                var request:URLRequest=new URLRequest(url);
                //form表单提交,同时声明分隔符boundary
                request.contentType="multipart/form-data; boundary="+UploadPostHelper.getBoundary();
                request.requestHeaders.push(new URLRequestHeader( 'Cache-Control', 'no-cache'));
                request.method=URLRequestMethod.POST;
                //设置上传文件名和上传数据

                //getPostData()方法主要是根据RFC1867来处理数据
                request.data=UploadPostHelper.getPostData("test.jpg",data );
               
                var loader:URLLoader = new URLLoader();
                loader.dataFormat=URLLoaderDataFormat.BINARY;
                loader.addEventListener(Event.COMPLETE, onComplete);
                loader.addEventListener(IOErrorEvent.IO_ERROR,onIOErr);
                loader.addEventListener(SecurityErrorEvent.SECURITY_ERROR,onSecurity);
                loader.load(request);
            }

 

-----------------------

UploadPostHelper.as

 

package fx.util
{
    import flash.events.*;
    import flash.net.*;
    import flash.utils.ByteArray;
    import flash.utils.Endian;
   
    /**
     * Take a fileName, byteArray, and parameters object as input and return ByteArray post data suitable for a UrlRequest as output
     *
     * @see http://marstonstudio.com/?p=36
     * @see http://www.w3.org/TR/html4/interact/forms.html
     * @see http://www.jooce.com/blog/?p=143
     * @see http://www.jooce.com/blog/wp%2Dcontent/uploads/2007/06/uploadFile.txt
     * @see http://blog.je2050.de/2006/05/01/save-bytearray-to-file-with-php/
     *
     * @author Jonathan Marston
     * @version 2007.08.19
     *
     * This work is licensed under a Creative Commons Attribution NonCommercial ShareAlike 3.0 License.
     * @see http://creativecommons.org/licenses/by-nc-sa/3.0/
     *
     */
    public class UploadPostHelper {
       
        /**
         * Boundary used to break up different parts of the http POST body
         */
        private static var _boundary:String = "";
       
        /**
         * Get the boundary for the post.
         * Must be passed as part of the contentType of the UrlRequest
         */
        public static function getBoundary():String {
           
            if(_boundary.length == 0) {
                for (var i:int = 0; i < 0x20; i++ ) {
                    _boundary += String.fromCharCode( int( 97 + Math.random() * 25 ) );
                }
            }
           
            return _boundary;
        }
       
        /**
         * Create post data to send in a UrlRequest
         * @param fileName:String 上传文件的名字 "xxx.txt/xxx.jpg/xxx.pdf"
         * @param byteArray:ByteArray 上传文件的文件内容
         * @param uploadDataFieldName:String 上传数据字段的名字 默认值=filedata
         * @param parameters:Object 参数 默认值=null
         */
        public static function getPostData(fileName:String, byteArray:ByteArray, uploadDataFieldName:String = "filedata", parameters:Object = null):ByteArray {
           
            var i: int;
            var bytes:String;
           
            var postData:ByteArray = new ByteArray();
            //更改或读取数据的字节顺序
            postData.endian = Endian.BIG_ENDIAN;
           
            //add Filename to parameters
            if(parameters == null) {
                parameters = new Object();
            }
            //设置上传文件名到parameters里
            parameters.Filename = fileName;
           
            //遍历parameters中的属性
            //add parameters to postData
            for(var name:String in parameters) {
                postData = BOUNDARY(postData);
                postData = LINEBREAK(postData);
                bytes = 'Content-Disposition: form-data; name="' + name + '"';
                for ( i = 0; i < bytes.length; i++ ) {
                    postData.writeByte( bytes.charCodeAt(i) );
                }
                postData = LINEBREAK(postData);
                postData = LINEBREAK(postData);
                postData.writeUTFBytes(parameters[name]);
                postData = LINEBREAK(postData);
            }
           
            //add Filedata to postData
            postData = BOUNDARY(postData);
            postData = LINEBREAK(postData);
            bytes = 'Content-Disposition: form-data; name="'+uploadDataFieldName+'"; filename="';
            for ( i = 0; i < bytes.length; i++ ) {
                postData.writeByte( bytes.charCodeAt(i) );
            }
            postData.writeUTFBytes(fileName);
            postData = QUOTATIONMARK(postData);
            postData = LINEBREAK(postData);
            bytes = 'Content-Type: application/octet-stream';
            for ( i = 0; i < bytes.length; i++ ) {
                postData.writeByte( bytes.charCodeAt(i) );
            }
            postData = LINEBREAK(postData);
            postData = LINEBREAK(postData);
            postData.writeBytes(byteArray, 0, byteArray.length);
            postData = LINEBREAK(postData);
           
            //add upload filed to postData
            postData = LINEBREAK(postData);
            postData = BOUNDARY(postData);
            postData = LINEBREAK(postData);
            bytes = 'Content-Disposition: form-data; name="Upload"';
            for ( i = 0; i < bytes.length; i++ ) {
                postData.writeByte( bytes.charCodeAt(i) );
            }
            postData = LINEBREAK(postData);
            postData = LINEBREAK(postData);
            bytes = 'Submit Query';
            for ( i = 0; i < bytes.length; i++ ) {
                postData.writeByte( bytes.charCodeAt(i) );
            }
            postData = LINEBREAK(postData);
           
            //closing boundary
            postData = BOUNDARY(postData);
            postData = DOUBLEDASH(postData);
           
            return postData;
        }
       
        /**
         * Add a boundary to the PostData with leading doubledash 添加以双破折号开始的分隔符
         */
        private static function BOUNDARY(p:ByteArray):ByteArray {
            var l:int = UploadPostHelper.getBoundary().length;
           
            p = DOUBLEDASH(p);
            for (var i:int = 0; i < l; i++ ) {
                p.writeByte( _boundary.charCodeAt( i ) );
            }
            return p;
        }
       
        /**
         * Add one linebreak 添加空白行
         */
        private static function LINEBREAK(p:ByteArray):ByteArray {
            p.writeShort(0x0d0a);
            return p;
        }
       
        /**
         * Add quotation mark 添加引号
         */
        private static function QUOTATIONMARK(p:ByteArray):ByteArray {
            p.writeByte(0x22);
            return p;
        }
       
        /**
         * Add Double Dash 添加双破折号--
         */
        private static function DOUBLEDASH(p:ByteArray):ByteArray {
            p.writeShort(0x2d2d);
            return p;
        }
       
    }

}

  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
ElementUI提供了一个el-upload组件用于上传文件,包括图片。以下是一个简单的示例: ```html <template> <div> <el-upload class="avatar-uploader" action="//jsonplaceholder.typicode.com/posts/" :show-file-list="false" :on-success="handleSuccess" :before-upload="beforeUpload"> <img v-if="imageUrl" :src="imageUrl" class="avatar"> <i v-else class="el-icon-plus avatar-uploader-icon"></i> </el-upload> </div> </template> <script> export default { data() { return { imageUrl: '' // 上传成功后图片的地址 } }, methods: { handleSuccess(response, file, fileList) { this.imageUrl = URL.createObjectURL(file.raw); // 使用本地地址作为图片地址 }, beforeUpload(file) { const isJPG = file.type === 'image/jpeg'; const isPNG = file.type === 'image/png'; const isLt2M = file.size / 1024 / 1024 < 2; if (!isJPG && !isPNG) { this.$message.error('只能上传 JPG/PNG 格式的图片'); } if (!isLt2M) { this.$message.error('上传图片大小不能超过 2MB'); } return isJPG || isPNG && isLt2M; } } } </script> <style scoped> .avatar-uploader { display: flex; justify-content: center; align-items: center; width: 128px; height: 128px; border-radius: 50%; background-color: #f5f5f5; overflow: hidden; } .avatar { width: 100%; height: 100%; object-fit: cover; } .avatar-uploader-icon { font-size: 28px; color: #8c939d; } </style> ``` 在上面的示例中,我们使用了el-upload组件来实现图片上传功能。我们设置了action属性为一个API接口,用于后端处理上传的文件,这里我们使用了jsonplaceholder提供的虚拟API。当用户选择了一张图片后,我们会先判断图片是否符合要求,如果不符合则会弹出提示框,否则会调用handleSuccess方法来处理上传成功后的回调。在handleSuccess方法中,我们使用URL.createObjectURL方法将本地图片地址作为图片的地址,从而展示上传的图片。

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值