'2016/11/12'에 해당되는 글 3건

HTML, javaScript, jQuery 는 Client에서 해석하는 언어이고, PHP는 서버와의 통신을 위한 스크립트 언어다.

서버상에서 가져온 파일을 읽으려면 클라이언트에서 인식할 수 있도록 해줘야 한다.

아니면 PHP 코드를 HTML 파일보다 먼저 읽어들이도록 위치를 위에다 놓은 것도 방법이다.


눈에 보이지 않게 <div id="div1" data-lat="<?php echo $lat;?>"></div> 를 이용해서 PHP 변수를 기록하면, HTML 에 기록된 내용을 jQuery, javaScript 에서 읽어올 수 있다.


PHP 변수를 받는 방법은 다른 파일에서 넘겨준 걸 읽을 때는 $_GET, $_POST 배열로 받아서 처리하면 된다.

아니면 직접 include_once '읽고자하는 파일'; 을 지정해주고 파일을 include 하면 해당 파일의 변수가 인식된다.


속성값 읽어오기

자바스크립트에서는 document.getElementById('div1').getAttribute('data-lat');

jQuery 에서는 $("#div1").attr('data-lat');


속성값 변경하기

자바스크립트에서는 document.getElementById('div1').setAttribute('data-lat','변경할값');

jQuery 에서는 $("#div1").attr('data-lat','변경할값');


DB에서 테이블 형태로 읽어온 걸 화면에 표시하고 테이블내 한 행의 게시글의 특정 정보를 알아내고자 할 때에는 this 를 사용한다.

group=$(this).attr('data-group');


==== 예제 파일 =====

<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8">
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.1.1/jquery.min.js"></script>
<script>
$(document).ready(function(){ // html 문서를 다 읽어들인 후
    //var lat = $("#div1").attr('data-lat'); // jQuery 방식
    var lat = document.getElementById('div1').getAttribute('data-lat'); // javaScript 방식
    var lon = $("#div2").attr('data-lon');
    alert("lat:"+ lat +" lon:"+ lon);
});
</script>
<body>
<?php
//include_once 'getPHP.php'; 다른 파일 내용을 읽어오고자 할 때
$lat = 33.4505296;
$lon = 126.570667;
?>
<div id="div1" data-lat="<?php echo $lat;?>"></div>
<div id="div2" data-lon="<?php echo $lon;?>"></div>
</body>
</html>

728x90
블로그 이미지

Link2Me

,

C# Web 파일을 PC에 다운로드하기 위해 만든 함수다.

사용법은 Web 파일 다운로드 게시글을 참조하면 된다.


코드

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.IO;

namespace NameSpace
{
    class Folder
    {
        public static void MyFolderCreate(string myfolder)
        {
            string MyPath = MyFolder(myfolder);
            if (!Directory.Exists(MyPath))
            {
                Directory.CreateDirectory(MyPath);
            }
        }

        public static string MyFolder(string myfolder)
        {
            string UserPath = Environment.GetFolderPath(Environment.SpecialFolder.MyDocuments); // User Documents 폴더
            return UserPath + "\\" + myfolder;
        }

        public static string MyfilePath(string myfolder, string appName)
        {
            return Folder.MyFolder(myfolder) + "\\" + appName;
        }

        public static void MyFolderDelete(string path)
        {
            DeleteDirectory(path, false);
        }

        public static void DeleteDirectory(string path, bool recursive)
        {
            if (recursive)
            {
                var subfolders = Directory.GetDirectories(path);
                foreach (var subfolder in subfolders)
                {
                    DeleteDirectory(subfolder, recursive);
                }
            }

            // Get all files of the folder
            var files = Directory.GetFiles(path);
            foreach (var file in files)
            {
                var attribute = File.GetAttributes(file);
                if ((attribute & FileAttributes.ReadOnly) == FileAttributes.ReadOnly)
                {
                    File.SetAttributes(file, attribute ^ FileAttributes.ReadOnly);
                }
                File.Delete(file);
            }
            Directory.Delete(path);
        }

        public static string SSplit(string _body, string _parseString, int index)
        {
            // 엑셀 VBA 에서 사용하는 Split 함수처럼 만든 사용자 함수
            string varTemp = _body.Split(new string[] { _parseString }, StringSplitOptions.None)[index];
            return varTemp;
        }
    }
}


728x90
블로그 이미지

Link2Me

,

C#에서 Web 방식으로 파일을 다운로드하는 코드이다.

오래되어 기억은 가물가물하지만 구글링도하고 블로그 검색으로 찾은 걸 약간 수정한거 같기는 하다.

최근에 SSD 이상증상으로 데이터를 살리지 못한 경험도 있고 해서 블로그에 기록해둔다.


사용법 예시

사용법 예시는 전체적으로 동작되는 걸 보여주는게 아니라 이런식으로 활용할 수 있다는 것만 간략하게 기록


private void webFileDown(string mp3sub, string mp3file)
{
    // 파일 다운로드
    string webfilePath = string.Format("http://ipaddress/{0}/{1}", mp3folder, mp3file);
    string localfilePath = Folder.MyfilePath("abcdef", mp3file);
    if (webFile.WebExists(webfilePath))
    {
        int write = webFile.DownloadFile(webfilePath, localfilePath);  // 파일 사이즈를 반환
    }
    else
    {
        MessageBox.Show("다운받을 파일이 존재하지 않습니다");
        return;
    }
}             



코드

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.IO;
using System.Net;
using System.Windows.Forms;

namespace NameSpace  // 수정해서 사용 필요
{
    class webFile
    {
        /// <summary>
        /// 웹파일 다운로드
        /// </summary>
        /// <param name="remoteFilename">웹 서버 파일</param>
        /// <param name="localFilename">PC 저장 파일</param>
        /// <returns>파일 크기를 반환</returns>
        public static int DownloadFile(String remoteFilename, String localFilename)
        {
            // Function will return the number of bytes processed to the caller. Initialize to 0 here.
            int bytesProcessed = 0;

            // Assign values to these objects here so that they can be referenced in the finally block
            Stream remoteStream = null;
            Stream localStream = null;
            WebResponse response = null;

            // Use a try/catch/finally block as both the WebRequest and Stream classes throw exceptions upon error
            try
            {
                WebRequest request = WebRequest.Create(remoteFilename); // 원격 파일 다운을 위한 객체 생성
                if (request != null)
                {
                    response = request.GetResponse(); // 서버로부터 WebResponse 오브젝트 받아옴
                    if (response != null)
                    {
                        // Once the WebResponse object has been retrieved, get the stream object associated with the response's data
                        remoteStream = response.GetResponseStream();
                        //localStream = File.Create(localFilename);  // local File 생성
                        localStream = new FileStream(localFilename, FileMode.OpenOrCreate, FileAccess.ReadWrite);

                        byte[] buffer = new byte[1024];  // 1k 버퍼 할당
                        int bytesRead;

                        // Simple do/while loop to read from stream until no bytes are returned
                        do
                        {
                            bytesRead = remoteStream.Read(buffer, 0, buffer.Length); // 1K 바이트씩 데이터 읽기
                            localStream.Write(buffer, 0, bytesRead); // PC에 데이터 저장
                            bytesProcessed += bytesRead;  // 전체 바이트 수 체크를 위해 누적
                        } while (bytesRead > 0);
                    }
                }
            }
            catch (Exception ex)
            {
                MessageBox.Show(ex.Message);
            }
            finally
            {
                if (response != null) response.Close(); //WebResponse객체 Close
                if (remoteStream != null) remoteStream.Close();
                if (localStream != null) localStream.Close();
            }

            return bytesProcessed;  // 수신한 전체 바이트수를 리턴(파일의 크기)
        }

        /// <summary>
        /// 웹에 파일이 존재하는지 검사하여 있으면 true 반환
        /// </summary>
        /// <param name="url">Web 파일 경로</param>
        /// <returns></returns>
        public static bool WebExists(string url)
        {
            bool ret = true;
            if (url == null)
                return false;
            HttpWebResponse response = null;
            try
            {
                var request = (HttpWebRequest)WebRequest.Create(url);
                request.Method = "HEAD";
                response = (HttpWebResponse)request.GetResponse();
            }
            catch (WebException)
            {
                ret = false;
            }
            finally
            {
                if (response != null)
                {
                    response.Close();
                }
            }
            return ret;
        }


    }
}


728x90

'C# > 통신' 카테고리의 다른 글

C# 과 Web  (0) 2018.03.10
C# Web 접속 로그인함수 만들기(HttpClient 방식)  (0) 2016.11.14
C# GetAsyncDataFromWeb  (0) 2016.08.21
C# GetDataFromWeb 사용자 함수  (0) 2016.08.20
C# comboBox 에 Text, Value 추가 및 POST, JSON  (0) 2016.08.19
블로그 이미지

Link2Me

,