Top / Programming / Python / Python CGI�v���O���~���O���� / �t�@�C�����A�b�v���[�h����

�t�@�C�����A�b�v���[�h����

�t�@�C���I���R���g���[���őI�����ꂽ�t�@�C�����A�b�v���[�h���܂��B

test15.cgi

#!/usr/bin/python
# -*- coding: utf-8 -*-
'''
�t�@�C�����A�b�v���[�h����
'''
html = '''Content-Type: text/html

<html>
<head>
  <meta http-equiv="Content-Type" content="text/html" charset="UTF-8" />
  <title>�t�@�C�����A�b�v���[�h����</title>
</head>
<body>
<h1>�t�@�C�����A�b�v���[�h����</h1>
<p>%s</p>
<form action="test15.cgi" method="post" enctype="multipart/form-data">
  <input type="file" name="file" />
  <input type="submit" />
</form>
</body>
</html>
'''

import cgi
import os, sys

try:
    import msvcrt
    msvcrt.setmode(0, os.O_BINARY)
    msvcrt.setmode(1, os.O_BINARY)
except ImportError:
    pass

result = ''
form = cgi.FieldStorage()
if form.has_key('file'):
    item = form['file']
    if item.file:
        fout = file(os.path.join('/tmp', item.filename), 'wb')
        while True:
            chunk = item.file.read(1000000)
            if not chunk:
                break
            fout.write(chunk)
        fout.close()
        result = '�A�b�v���[�h���܂����B'

print html % result

���

try:
    import msvcrt
    msvcrt.setmode(0, os.O_BINARY)
    msvcrt.setmode(1, os.O_BINARY)
except ImportError:
    pass

msvcrt���W���[����Windows�ł̂ݎg�p�ł��郂�W���[���ł��B

 msvcrt.setmode(0, os.O_BINARY)
 msvcrt.setmode(1, os.O_BINARY)

�t�@�C���̓ǂݍ��݂��������݂��o�C�i�����[�h�ɐݒ肵�܂��B ���̏�����Windows�̂ݕK�v�ɂȂ�܂��B

import cgi
f = cgi.FieldStorage()

HTML�t�H�[�����瑗�M���ꂽ�l�́Acgi���W���[����FieldStorage�N���X���g�p���Ď擾���܂��B

if form.has_key('file'):
    item = form['file']
    if item.file:

if form.has_key('file') �Œl�����݂��邱�Ƃ��m�F���Aitem = form['file'] �� FieldStorage �N���X�̃C���X�^���X���擾���܂��B

if item.file: �Ńt�@�C���̃f�[�^�����݂��邱�Ƃ��m�F���܂��Bitem.file �̓t�@�C���łȂ���� None ��Ԃ��܂��B

 fout = file(os.path.join('/tmp', item.filename), 'wb')

item.filename ��file�̃R���g���[���ɑ΂��ăN���C�A���g���ݒ肵���t�@�C������Ԃ��܂��B

os.path.join() �́A���̃v���b�g�t�H�[���œK�؂ȃp�X��؂蕶���ŘA�������������Ԃ��܂��B

file(filename, mode) �� filename �Ŏw�肳�ꂽ�t�@�C���� mode �̃��[�h�ŊJ���܂��B

�����ł́A/tmp�t�H���_�ɑI�����ꂽ�t�@�C�����Ńt�@�C�����쐬���܂��B

 while True:
     chunk = item.file.read(1000000)
     if not chunk:
         break
     fout.write(chunk)
 fout.close()

�A�b�v���[�h���ꂽ�f�[�^����1000000�o�C�g�ǂݍ��݂܂��B

if not chunk:
    break

�ǂݍ��ރf�[�^���Ȃ��Ȃ�΁A���[�v�𔲂��܂��B

fout.write(chunk)

�ǂݍ��񂾃f�[�^���t�@�C���ɏ������݂܂��B

fout.close()

�������݂��I��������t�@�C����‚��܂��B

�֘AURL

�X�V����