Django에서 CSV 파일을 서버에 업로드를 할 때 이용한 방법이다.
view에서 input type='file'의 name을 이용해서 파일 정보를 받는다.
Url에서 /uploadcsvfile의 주소는 view의 uploadCSVfile 함수이다.
참고사이트: http://hanjiq.egloos.com/2373084
JQuery Form Plugin: http://jquery.malsup.com/form/
Plugin download site: http://jquery.malsup.com/form/#download
1. Html
<form name='csv_form' id='csv_form' method='POST' enctype='multipart/form-data'>
{% csrf_token %}
<input type='file' id='upload_file' name='upload_file' style='width: 300px;' />
<button id='csv_file_upload_button' class='uploader_btn' style='display:inline;'
onclick='FileUpload()'>올리기</button>
</form>
|
2. JavaScript
<script type='text/javascript'>
//파일전송 후 콜백 함수
function FileuploadCallback(data,state){
if (data=="error"){
alert("파일전송중 오류가 발생하였습니다.\n다시한번 시도해주세요.");
return false;
}
alert("파일전송이 완료되었습니다.");
}
$(function(){
//비동기 파일 전송
var frm=$('#csv_form');
frm.ajaxForm(FileuploadCallback);
frm.submit(function(){return false; });
});
// 파일업로드 이벤트
function FileUpload() {
if(!$("#upload_file").val()){
alert("파일을 선택하세요.");
$("#upload_file").focus();
return;
}
//파일전송
var frm;
frm = $('#csv_form');
frm.attr("action","/uploadcsvfile");
frm.submit();
}
</script>
|
3. View.py
def uploadCSVfile(request):
response = {}
if request.method == 'POST':
f = request.FILES['upload_file']
data = [row for row in csv.reader(f.read().splitlines())] # csv file parsing
handle_uploaded_file(f) #file save
response = {'success': True}
else:
response = {'success': False}
return HttpResponse(json.dumps(response))
def handle_uploaded_file(f):
path = settings.MEDIA_ROOT + '/data/order/'
if not os.path.exists(path):
os.makedirs(path)
fn = path + 'temp.csv'
with open(fn, 'wb+') as destination:
for chunk in f.chunks():
destination.write(chunk)
|
LIST
'Python and Django' 카테고리의 다른 글
| PHP's explode() 함수를 Python으로 처리할 경우 (0) | 2013.01.07 |
|---|---|
| Apache와 Django 연결 (0) | 2012.11.29 |
| Python 이차원배열 생성 방법 (0) | 2012.10.18 |
| PIL을 이용한 그리기 part. 1 (0) | 2012.09.06 |
| PIL을 이용한 이미지 편집 part.1 (0) | 2012.09.05 |