반응형

점점 주제가 시스템 트레이딩이랑 멀어지는 것 같지만.

매일 장이 끝나고 귀여운 캐릭터가 오늘 매매결과를 알려주면 좋지않을까 싶어서 만들어 보았다.

 

지난번에 라인으로 메시지를 보내는것은 구글링으로 어떻게 찾아냈는데 이미지 보내는 코드는 아무리 찾아봐도 없다.

파이썬으로 된 코드는 많은데 왜 C#은...

C#에서 파이썬 연동을 해야하나 고민해봤지만 파이썬 설치해야하는게 귀찮아서 패스

그러다가 HttpWebRequest로 파일업로드 하는 방법을 검색해보니 꽤 나온다. 

 

https://stackoverflow.com/questions/566462/upload-files-with-httpwebrequest-multipart-form-data

 

Upload files with HTTPWebrequest (multipart/form-data)

Is there any class, library or some piece of code which will help me to upload files with HTTPWebrequest? Edit 2: I do not want to upload to a WebDAV folder or something like that. I want to sim...

stackoverflow.com

 

그래봐야 내가 이해를 못하는 코드는 수정을 못하는데 뭐...

쉬워보이는 코드 이리저리 수정하길 2시간.

됐다!

 

 

코드


        private void lineNotify(string msg, string file)
        {
            
            string token = "토큰 수정 필요";
            PostMultipart(token, "https://notify-api.line.me/api/notify",
                    new Dictionary<string, object>() {
                     { "message", msg },
                     { "imageFile", new FormFile() { Name = "image.jpg", ContentType = "image/jpeg", FilePath = file }
                        }});


        }


        public class FormFile
        {
            public string Name { get; set; }

            public string ContentType { get; set; }

            public string FilePath { get; set; }

            public Stream Stream { get; set; }
        }



        public static string PostMultipart(string token, string url, Dictionary<string, object> parameters)
        {

            string boundary = "---------------------------" + DateTime.Now.Ticks.ToString("x");
            byte[] boundaryBytes = System.Text.Encoding.ASCII.GetBytes("\r\n--" + boundary + "\r\n");

            HttpWebRequest request = (HttpWebRequest)WebRequest.Create(url);
            request.ContentType = "multipart/form-data; boundary=" + boundary;
            request.Method = "POST";
            request.KeepAlive = true;
            request.Credentials = System.Net.CredentialCache.DefaultCredentials;
            request.Headers.Add("Authorization", "Bearer " + token);

            if (parameters != null && parameters.Count > 0)
            {

                using (Stream requestStream = request.GetRequestStream())
                {

                    foreach (KeyValuePair<string, object> pair in parameters)
                    {

                        requestStream.Write(boundaryBytes, 0, boundaryBytes.Length);
                        if (pair.Value is FormFile)
                        {
                            FormFile file = pair.Value as FormFile;
                            string header = "Content-Disposition: form-data; name=\"" + pair.Key + "\"; filename=\"" + file.Name + "\"\r\nContent-Type: " + file.ContentType + "\r\n\r\n";
                            byte[] bytes = System.Text.Encoding.UTF8.GetBytes(header);
                            requestStream.Write(bytes, 0, bytes.Length);
                            byte[] buffer = new byte[32768];
                            int bytesRead;
                            if (file.Stream == null)
                            {
                                // upload from file
                                using (FileStream fileStream = File.OpenRead(file.FilePath))
                                {
                                    while ((bytesRead = fileStream.Read(buffer, 0, buffer.Length)) != 0)
                                        requestStream.Write(buffer, 0, bytesRead);
                                    fileStream.Close();
                                }
                            }
                            else
                            {
                                // upload from given stream
                                while ((bytesRead = file.Stream.Read(buffer, 0, buffer.Length)) != 0)
                                    requestStream.Write(buffer, 0, bytesRead);
                            }
                        }
                        else
                        {
                            string data = "Content-Disposition: form-data; name=\"" + pair.Key + "\"\r\n\r\n" + pair.Value;
                            byte[] bytes = System.Text.Encoding.UTF8.GetBytes(data);
                            requestStream.Write(bytes, 0, bytes.Length);
                        }
                    }

                    byte[] trailer = System.Text.Encoding.ASCII.GetBytes("\r\n--" + boundary + "--\r\n");
                    requestStream.Write(trailer, 0, trailer.Length);
                    requestStream.Close();
                }
            }

            using (WebResponse response = request.GetResponse())
            {
                using (Stream responseStream = response.GetResponseStream())
                using (StreamReader reader = new StreamReader(responseStream))
                    return reader.ReadToEnd();
            }


        }

 

토큰은 전에 올렸던 글에서 말했듯 개인적으로 발급받아 수정하면 된다.

그리고 lineNotify() 에 massage 와 image파일 경로를 전달해주면 실행이 된다.

이미지파일만 보내는건 안된다. 메시지도 같이 보내야만한다. 라인에서 막아놨음.

이미지 파일은 png 과 jpeg 만 가능하고 1시간단위로 업로드 제한이 있다고 한다.

자세한건 https://notify-bot.line.me/doc/en/ (LINE Notify API Document) 참고

 

실행사진

 

잘안돼서 시바시바 거리다가 마무리는 조유리로

잠와서 글쓸 기력도 없다

뿅.

반응형

+ Recent posts