메뉴 건너뛰기

imp

[GS] apps script 를 이용한 구글 드라이브로 파일 업로드

lispro062017.04.09 21:21조회 수 2331댓글 0

    • 글자 크기

PHP 를 이용한 파일 업로드는 서버에 저장된 파일을 스크립트를 이용해 리스트와 파일로 저장하는 방식이었다.


이제는 apps script를 이용해 직접 구글 드라이브로 업로드하여 중간 절차와 서버 사용 부담을 줄였다.


[원본글]

https://ctrlq.org/code/19747-google-forms-upload-files


[file.gs]

/* The script is deployed as a web app and renders the form */

function doGet(e) {

  return HtmlService

    .createHtmlOutputFromFile('form.html')

    .setTitle("파일 업로드");

}


function uploadFileToGoogleDrive(data, file, name, kind, row) {


  try {


    var tD = Utilities.formatDate(new Date(), "GMT+9", "yyyyMMdd");

    var folder, folders = DriveApp.getFoldersByName(tD);

    var imageFolder = DriveApp.getFolderById("폴더");

    /* Find the folder, create if the folder does not exist */

    if (folders.hasNext()) {

      folder = folders.next();

    } else {

      folder = imageFolder.createFolder(tD);

    }


    var contentType = data.substring(5,data.indexOf(';')),

        bytes = Utilities.base64Decode(data.substr(data.indexOf('base64,')+7)),

        blob = Utilities.newBlob(bytes, contentType, file);


    var file = folder.createFolder(tD).createFile(blob);

    

    return "OK";


  } catch (f) {

    return f.toString();

  }


}


[form.html]

<!-- File upload button -->

<input id="file" type="file">

<!-- Form submit button -->

<button id="sb" onclick="submitForm();return false;">전송</button>

<!-- Show Progress -->

<div id="progress"></div>

<!-- Add the jQuery library -->

<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.7.2/jquery.min.js"></script>


<script>


  var file, 

      reader = new FileReader();


  // Upload the file to Google Drive

  reader.onloadend = function(e) {

    google.script.run

      .withSuccessHandler(showMessage)

      .uploadFileToGoogleDrive(

         e.target.result, file.name, 

         $('select#company option:selected').text(), 

         $('select#kind').val(), 

         $('select#company').val()

      );

  };


  // Read the file on form submit

  function submitForm() {

      file = $('#file')[0].files[0];

      if(!file){

        alert('파일선택');

      }else{

        file = $('#file')[0].files[0];

        showMessage("Uploading file..");

        reader.readAsDataURL(file);

      }

  }


  function showMessage(e) {

    $('#progress').html(e);

    $('#sb').prop("disabled",true);

  }


</script>

lispro06 (비회원)
    • 글자 크기

댓글 달기

[Tip] Windows NT/2000/XP/2003/Vista 비밀번호 분실 해제

[원문보기]
비밀번호를 잊었다면.


아래의 과정을 시작한다.




버전에 따라서 Password & Registry Tools 번호가 다를 수 있다.



9.9를 이용하길 추천한다.



아래 화면에서 1이나 2를 통해 OS를 찾는다.



얼마간의 시간이 지나면
 
아래와 같이 발견된 sam 파일을 표시한다.


원하는 계정을 선택하고


Y를 누르면 완료된다.


Esc로 빠져나간 후 재부팅 하면 password가 해제된 것을 확인할 수 있다.

[XML] Dublin Core(DC)

[원문보기]
개념
 1995년 OCLC(Online Computer Library Center)와 NCSA(National Centre for Supercomputer Application)가 더블린(Dublin)에서 개최한 워크숍에서 합의된 메타 데이타
 데이타의 호환성을 유지
 네트웍크 자원의 기술에 필요한 일련의 데이타 요소를 규정
 자원의 신속한 검색 지원
목적
 데이타의 형식/구조 단순화
 원문의 저자나 발행자
 메타 데이타를 직접 작성
 네트웍크 출판을 위한 저작도구의 개발자
 메타 데이타에 대한 템플릿을 직접 소프트웨어에 포함할 수 있도록 
 작성된 데이타를 기초로 특정 분야에서 요구되는 상세한 수준으로 확장 사용  

 Dublin Core 15개 데이터 요소  
 콘텐츠 기술(내용) 요소지적속성요소 물리적 기술(구현)요소 
 Title(표제)
Subject(주제)
Description(설명)
Source(출전)
Language(언어)
Relation(관련자료)
Coverage(내용범위)
Creator(제작자)
Publisher(발행처)
Contributor(기타제작자)
Right(이용조건)
 Date(발행일자)
Type(자료유형)
Format(형식)
Identifier(식별자)

[PPT] 파워포인트 전체 페이지 넣는 VBA 스크립트

[원문보기]
반드시 해야할 것.
마스터 보기에서 삽입->머리글/바닥글
바닥글의 체크박스를 체크하고, 모두적용을 클릭함.
아래 그림과 같이, "바닥글"영역이 존재해야 error가 나지 않음.(for문의 시작을 2로 했기 때문에 첫 슬라이드는 바닥글이 존재하지 않아도 됨)^^V



1. Alt+F11(Visual Basic Editor)
2. 삽입 -> 모듈
3. 모듈창에 아래와 같이 입력
4. 실행(F5)하면 바닥글 위치에 표시됩니다.

Sub dhUserPage()
    Dim i As Integer, j As Integer
   
    With ActivePresentation
        If .Slides.Count > 1 Then
            For i = 2 To .Slides.Count
                .Slides(i).HeadersFooters.Footer.Text = i & "/" & .Slides.Count
            Next i
        End If
    End With
End Sub

[창업일지] 통신판매업 폐업신고

[원문보기]
계양구청 지역경제과에서 계속 전화해서, 몸소 갔다왔다. 제길슨... 폐업신고서를 역시 작성해서 원본과 함께 민원여권과 4번 창구에 제출함.T.T;;;

[창업일지] 폐업신고

[원문보기]
 사업자등록증 원본을 들고가서, 폐업신고서와 함께 제출하면 끝!

 뭐야.. 별거 아니잖아...

 잠깐 실업급여나 신청해 볼까.. 음... 좀 더 알아보고....

[WCAG] 플래시 대체 텍스트

[원문보기]
<script type="text/javascript">
function flash(swfWidth,swfHeight,swf_src){
        var flash_tag = "";
        flash_tag = '<object classid="clsid:D27CDB6E-AE6D-11cf-96B8-444553540000" ';
        flash_tag +='codebase="http://download.macromedia.com/pub/shockwave/cabs/flash/swflash.cab#version=8,0,0,0" ';
        flash_tag +='width="'+swfWidth+'" height="'+swfHeight+'" >';
        flash_tag +='<param name="wmode" value="transparent">';
        flash_tag +='<param name="movie" value="'+swf_src+'">';
        flash_tag +='<param name="scale" value="exactfit">';
        flash_tag +='<param name="quality" value="high">';
        flash_tag +='<embed src="'+swf_src+'" quality="high" wmode="transparent" pluginspage="http://www.macromedia.com/go/getflashplayer" ';
        flash_tag +='type="application/x-shockwave-flash"  width="'+swfWidth+'" height="'+swfHeight+'"></embed></object>'
        document.write(flash_tag);
}

   <!--
    flash(150,120,"http://www.bloodinfo.net/images/v2/swf/main/blood_campaign/bood.swf");
   -->
   </script>
   <noscript>
    <strong>[헌혈 공익광고] 당신의 얼굴은 잠깐 찡그려 지지만, 누군가의 얼굴은 평생 활짝 피어납니다.</strong>
   </noscript>

플래시를 함수로 만들고, 실행한다. noscript라면, 대체 텍스트가 출력되도록 noscript 태그를 사용한다.

터보코드

[원문보기]
bdclose all;
set_param(0, 'CharacterEncoding', 'windows-1252');

simulink를 저장하기 전에 위와 같이 encoding을 변경해준다. 폴더나 파일명이 한글이면 안된다.

melfb.m

[원문보기]

function m = melfb(p, n, fs)
p=9;
n=2048;
fs=2000;
f0 = 700 / fs;
fn2 = floor(n/2);


lr = log(1 + 0.5/f0) / (p+1);


% convert to fft bin numbers with 0 for DC term
bl = n * (f0 * (exp([0 1 p p+1] * lr) - 1));


b1 = floor(bl(1)) + 1;
b2 = ceil(bl(2));
b3 = floor(bl(3));
b4 = min(fn2, ceil(bl(4))) - 1;


pf = log(1 + (b1:b4)/n/f0) / lr;
fp = floor(pf);
pm = pf - fp;


r = [fp(b2:b4) 1+fp(1:b3)];
c = [b2:b4 1:b3] + 1;
v = 2 * [1-pm(b2:b4) pm(1:b3)];


m = sparse(r, c, v, p, 1+fn2);
size_m = size(m);
plot(linspace(0, (fs/2), (n/2)+1),m);
%title('Mel-scale filter bank');
xlabel('Frequency (Hz)');
set(get(gca,'xlabel'),'FontSize',20);
ylabel('Amplitude');
set(get(gca,'ylabel'),'FontSize',20);
set(gca, 'XTick',[0:100:2000], 'XTickLabel',[0:100:1000],'fontsize',20);
set(gca, 'YTick',[0:1:2], 'YTickLabel',[0:1:2],'fontsize',20);

Hamming Window Amplitude Response

[원문보기]

% Chapter 7: Hamming Window Amplitude Response


%


M = 45; alpha = (M-1)/2;


n = -alpha:alpha;


w = (hamming(M))'; sumw = sum(w);


N = 1000; omega = (2*pi/N)*[-N/2:N/2];


Wr = real(w*(exp(-j*n'*omega)));


db = 20*log10(abs(Wr)/max(Wr));


IntWr = cumsum(Wr);


Intdb = 20*log10(abs(IntWr)/N);


k = (N/2+1) - min(find(Intdb > -53));


tr_width = 2*k*2*M/N, %actual transition width in pi/M units


omega1 = -(tr_width/2)/M; omega2 = (tr_width/2)/M;


%


% plots


subplot(1,1,1)


subplot(2,2,1); stem(n,w);


axis([-(alpha+8),(alpha+8),-0.1,1.1]);


set(gca,'YTickMode','manual','YTick',[0,1])


set(gca,'XTickMode','manual','XTick',[-22,0,22]);


title('Hamming Window : M=45')


xlabel('n'); ylabel('w(n)')


subplot(2,2,3); plot(omega/pi,Wr);


axis([-1,1,-2,sumw+5]);


set(gca,'YTickMode','manual','YTick',[0,sumw])


set(gca,'XTickMode','manual','XTick',[-1,0,1]); grid


set(gca,'XTickLabelMode','manual','XTickLabels',[' 0';'22';'45']);


title('Amplitude Response')


xlabel('frequency in pi units'); ylabel('Wr')


subplot(2,2,2); plot(omega/pi,db);


axis([-1,1,-60,10]);


set(gca,'YTickMode','manual','YTick',[-60,-42,0])


set(gca,'YTickLabelMode','manual','YTickLabels',['60';'43';' 0'])


set(gca,'XTickMode','manual','XTick',[-1,0,1]);grid


title('Amplitude Response in dB')


xlabel('frequency in pi units'); ylabel('Decibels')


subplot(2,2,4); plot(omega/pi,Intdb);


axis([-1,1,-70,10]);


set(gca,'YTickMode','manual','YTick',[-70,-54,0])


set(gca,'YTickLabelMode','manual','YTickLabels',['70';'54';' 0'])


set(gca,'XTickMode','manual','XTick',[-1;omega1;omega2;1]);grid


set(gca,'XTickLabelMode','manual','XTickLabels',['-1';'  ';'  ';' 1'])


title('Accumulated Amplitude Response')


xlabel('frequency in pi units'); ylabel('Decibels')


text(omega2,5,'Width=(6.6)*pi/M')

travelling salesman problem

[원문보기]
http://webscripts.softpedia.com/script/Miscellaneous/Traveling-Salesman-Problem-34479.html

배열의 사용
1. (:,1) 하면, 1열의 정보를 출력한다.
2. (1,:) 하면, 1행의 정보를 출력한다.
3. [mat mat(1)]하면, 첫행의 정보를 뒤에 덧붙인다.
4. zeros(2,4) 하면, 2x4의 0행렬을 만든다.
5. randperm(x)하면, 1~x까지의 랜덤한 자연수 배열을 만든다.
6. plot은 x,y의 2차 그래프를 그린다.
7. plot3는 x,y,z의 3차 그래프를 그린다.
8. text 함수는 임의의 위치에 문자를 출력한다.
9. colormap sets the current figure's colormap to MAP.
10. flipud함수는 아래와 같이 바꾼다.
  X = 1 4               3 6
        2 5               2 5
        3 6               1 4

flex 외부 변수 이용, 받기, 현재 url

[원문보기]
http://www.abdulqabiz.com/blog/archives/macromedia_flex/how_to_get_url.php

나는 제목과 같은 검색어로 꾸준히 찾았던 것 같다.

역시 방법은 있었다.

우....

친절하게 소스파일까지...ㅋㅋ

json encoding, decoding

[원문보기]
json에 관한, flex에 대해서도 흥미로운 자료가 많다.

그런데, 무작정 갖다 쓰는게 부담이 된다.. 또한 홍길동이 벌써 서른이라니.....

<?xml version="1.0" encoding="utf-8"?>
<mx:Application xmlns:mx="http://www.adobe.com/2006/mxml" layout="absolute" initialize="initApp()">
        <mx:Script>
                <![CDATA[
                        import com.adobe.serialization.json.JSON;
                        import mx.controls.Alert;
                        
                        private function initApp():void{
                                var obj:Object = new Object();
                                obj.name="홍길동";
                                obj.age=30;
                                
                                var json:String = JSON.encode(obj);
                                trace(json);
                                
                                var obj2:Object = JSON.decode(json);
                                mx.controls.Alert.show(json + obj2.name + "," + obj2.age);
                        }
                ]]>
        </mx:Script>
</mx:Application>

파일1은 flex관련 문서이고, file2는 flex용 json라이브러리이다.

창업일지 - 홈페이지에 CCL 표기

[원문보기]
라이센스에 대한 구분이 필요해졌다.

2008년 7월 16일 - 부가세 확정신고

[원문보기]
예정신고를 했기 때문에, 4~6월분만 했다.

활용한 함수

[원문보기]
set(handles.in_play,'enable','on');

속성을 변경한다.

if (strcmp(fs_ampl,' ') || str2num(fs_ampl)<=50)
    msgbox('50보다 큰 값을 입력하세요');

if의 여러 값을 체크하는 연산자


axes(handles.axes4);
plot(0,0);

plot을 0,0으로 하여, 초기화 효과를...

errordlg의 활용 matlab alert의 기능 수행

[원문보기]
errordlg

Create and display an error dialog box


Syntax


  • errordlg
    errordlg('errorstring')
    errordlg('errorstring','dlgname')
    errordlg('errorstring','dlgname','on')
    h = errordlg(...)

Description
Matlab의 alert이다. 찾느라 약간 시간이 걸렸다. 월......
on을 쓰면, 기존에 box가 있는 것을 체크하여 새로 띄우지 않는다.
h에는 handle을 저장하게 된다.

flex 페이지 이동

[원문보기]
<mx:Script>
 <![CDATA[
private function goUrl(URL:String):void {
    var url:URLRequest = new URLRequest(URL);
    var uv:URLVariables = new URLVariables();
    url.method = "GET";
   
    /**    
    * 파라메터 전달
    * 파라메터명 uv.파라메터명 = "파라메터값"
    */
 
    uv.board = "guest";
    uv.no= "100"; 
    url.data = uv;
    navigateToURL(url);
}
 ]]>
</mx:Script>
<mx:Button x="169" y="274" label="Button" click="goUrl('http://google.com');"/>

이런 간단한 것도 정리해야 나중에 쓸데가 있다. ㅋ
첨부 (0)
위로