예제 #1
0
        private void DownloadFile(string eTag, string localFileName)
        {
            var req = new http._Oss.GetSTSInfoReq()
            {
                UserId = Class1.UserId
            };
            var    resp = http._Oss.GetSTSInfo(req);
            Thread t    = new Thread(new ThreadStart(() =>
            {
                // 拿到STS临时凭证后,通过其中的安全令牌(SecurityToken)和临时访问密钥(AccessKeyId和AccessKeySecret)生成OSSClient。
                var client = new OssClient(Class1.EndPoint, resp.AccessKeyId, resp.AccessKeySecret, resp.SecurityToken);
                try
                {
                    var getObjectRequest = new GetObjectRequest(Class1.BucketName, eTag);
                    getObjectRequest.StreamTransferProgress += DownloadProgressCallback;
                    // 下载文件。
                    var ossObject = client.GetObject(getObjectRequest);
                    using (var stream = ossObject.Content)
                    {
                        var buffer    = new byte[1024 * 1024];
                        var bytesRead = 0;
                        var bw        = new BinaryWriter(new FileStream(localFileName, FileMode.OpenOrCreate, FileAccess.ReadWrite));
                        while ((bytesRead = stream.Read(buffer, 0, buffer.Length)) > 0)
                        {
                            bw.Write(buffer.Take(bytesRead).ToArray());
                        }
                        bw.Close();
                    }
                    Console.WriteLine("Get object:{0} succeeded", eTag);
                    Invoke(new Action(() =>
                    {
                        pgb_download.Value   = 100;
                        pgb_download.Visible = false;
                    }));
                }
                catch (OssException ex)
                {
                    Console.WriteLine("Failed with error code: {0}; Error info: {1}. \nRequestID:{2}\tHostID:{3}",
                                      ex.ErrorCode, ex.Message, ex.RequestId, ex.HostId);
                }
                catch (IOException e)
                {
                    Console.WriteLine(e.Message + "\n Cannot create file.");
                    return;
                }
                catch (Exception ex)
                {
                    Console.WriteLine("Failed with error info: {0}", ex.Message);
                }
            }));

            t.Start();
        }
예제 #2
0
        private void UploadFile(string localFileName)
        {
            var eTag = Class1.GenerateMD5WithFilePath(localFileName);
            var req  = new http._Oss.GetSTSInfoReq()
            {
                UserId = Class1.UserId
            };
            var resp = http._Oss.GetSTSInfo(req);

            Thread t = new Thread(new ThreadStart(() =>
            {
                // 拿到STS临时凭证后,通过其中的安全令牌(SecurityToken)和临时访问密钥(AccessKeyId和AccessKeySecret)生成OSSClient。
                var client = new OssClient(Class1.EndPoint, resp.AccessKeyId, resp.AccessKeySecret, resp.SecurityToken);
                if (!client.DoesObjectExist(Class1.BucketName, eTag))
                {
                    try
                    {
                        using (var fs = File.Open(localFileName, FileMode.Open))
                        {
                            var putObjectRequest = new PutObjectRequest(Class1.BucketName, eTag, fs);
                            putObjectRequest.StreamTransferProgress += UploadProgressCallback;
                            client.PutObject(putObjectRequest);
                        }
                        Console.WriteLine("Put object:{0} succeeded", eTag);
                    }
                    catch (OssException ex)
                    {
                        Console.WriteLine("Failed with error code: {0}; Error info: {1}. \nRequestID: {2}\tHostID: {3}",
                                          ex.ErrorCode, ex.Message, ex.RequestId, ex.HostId);
                    }
                    catch (Exception ex)
                    {
                        Console.WriteLine("Failed with error info: {0}", ex.Message);
                    }
                }
                Invoke(new Action(() =>
                {
                    pgb_upload.Value   = 100;
                    pgb_upload.Visible = false;
                }));

                var name            = Path.GetFileName(localFileName);
                var createObjectReq = new http._Object.CreateObjectReq()
                {
                    ETag = eTag,
                    Name = name
                };
                var createObjectResp = http._Object.CreateObject(createObjectReq);
                var objId            = createObjectResp.Id;
                Class1.InsertObjectIfNotExists(objId, eTag, name);

                var sendMessageReq = new http._Message.SendMessageReq()
                {
                    UserIdSend  = Class1.UserId,
                    IdRecv      = userIdChat,
                    Content     = objId.ToString(),
                    ContentType = (int)Class1.ContentType.Object,
                    MessageType = 0
                };
                var sendMessageResp = http._Message.SendMessage(sendMessageReq);
                var statusCode      = sendMessageResp.StatusCode;

                switch (statusCode)
                {
                case 1:
                    {
                        Class1.appendSysMsgToMsgBox(this, "你与" + $"{Class1.UserId2User[userIdChat].NickName}({userIdChat})" + "未成为好友,无法发送消息", DateTime.Now);
                        return;
                    }
                }

                var messageId  = sendMessageResp.Id;
                var createTime = sendMessageResp.CreateTime;
                var param      = Class1.Gzip(System.Text.Encoding.Default.GetBytes(objId.ToString()));
                var ret        = Class1.sql.ExecuteNonQueryWithBinary($"INSERT INTO `message`(id, user_id_send, user_id_recv, group_id, content, create_time, content_type, msg_type) VALUES({messageId}, " +
                                                                      $"{Class1.UserId}, {userIdChat}, 0, @param, {createTime}, {(int)Class1.ContentType.Object}, 0)", param);
                if (!ret)
                {
                    MessageBox.Show("DB错误,INSERT INTO message失败", "信息", MessageBoxButtons.OK, MessageBoxIcon.Warning);
                    return;
                }
                Class1.appendFileToMsgBox(this, $"{Class1.UserId2User[Class1.UserId].NickName}({Class1.UserId})", Class1.StampToDateTime(createTime), "[文件]" + name, objId);
            }));

            t.Start();
        }
예제 #3
0
        public static void UploadImage(string localFileName, long groupId, frm_group frmGroup)
        {
            var eTag = Class1.GenerateMD5WithFilePath(localFileName);
            var req  = new http._Oss.GetSTSInfoReq()
            {
                UserId = Class1.UserId
            };
            var resp = http._Oss.GetSTSInfo(req);

            Thread t = new Thread(new ThreadStart(() =>
            {
                // 拿到STS临时凭证后,通过其中的安全令牌(SecurityToken)和临时访问密钥(AccessKeyId和AccessKeySecret)生成OSSClient。
                var client = new OssClient(Class1.EndPoint, resp.AccessKeyId, resp.AccessKeySecret, resp.SecurityToken);
                if (!client.DoesObjectExist(Class1.BucketName, eTag))
                {
                    try
                    {
                        using (var fs = File.Open(localFileName, FileMode.Open))
                        {
                            var putObjectRequest = new PutObjectRequest(Class1.BucketName, eTag, fs);
                            //putObjectRequest.StreamTransferProgress += UploadProgressCallback;
                            client.PutObject(putObjectRequest);
                        }
                        Console.WriteLine("Put object:{0} succeeded", eTag);
                    }
                    catch (OssException ex)
                    {
                        Console.WriteLine("Failed with error code: {0}; Error info: {1}. \nRequestID: {2}\tHostID: {3}",
                                          ex.ErrorCode, ex.Message, ex.RequestId, ex.HostId);
                    }
                    catch (Exception ex)
                    {
                        Console.WriteLine("Failed with error info: {0}", ex.Message);
                    }
                }

                var name = Path.GetFileName(localFileName);

                var sendMessageReq = new http._Message.SendMessageReq()
                {
                    UserIdSend  = Class1.UserId,
                    IdRecv      = groupId,
                    Content     = eTag,
                    ContentType = (int)Class1.ContentType.Image,
                    MessageType = (int)Class1.MsgType.GroupChat
                };
                var sendMessageResp = http._Message.SendMessage(sendMessageReq);
                var statusCode      = sendMessageResp.StatusCode;

                switch (statusCode)
                {
                case 1:
                    {
                        cls_group.appendSysMsgToMsgBox(frmGroup, "你尚未加入群聊,无法发送消息", DateTime.Now);
                        return;
                    }
                }


                var messageId  = sendMessageResp.Id;
                var createTime = sendMessageResp.CreateTime;
                var param      = Class1.Gzip(System.Text.Encoding.Default.GetBytes(eTag));
                var ret        = Class1.sql.ExecuteNonQueryWithBinary($"INSERT INTO `message`(id, user_id_send, user_id_recv, group_id, content, create_time, content_type, msg_type) VALUES({messageId}, " +
                                                                      $"{Class1.UserId}, 0, {groupId}, @param, {createTime}, {(int)Class1.ContentType.Image}, {(int)Class1.MsgType.GroupChat})", param);
                if (!ret)
                {
                    MessageBox.Show("DB错误,INSERT INTO message失败", "信息", MessageBoxButtons.OK, MessageBoxIcon.Warning);
                    return;
                }
                var imageData  = Class1.LoadFile(localFileName);
                var imageParam = Class1.Gzip(imageData);
                Class1.InsertImageIfNotExists(eTag, imageParam);
                cls_group.appendImageToMsgBox(frmGroup, Class1.UserId.ToString(), Class1.StampToDateTime(createTime), imageData);
            }));

            t.Start();
        }