본문 바로가기
Python and Django

Django File upload

by leo21c 2013. 5. 28.
SMALL

Django에서 CSV 파일을 서버에 업로드를 할 때 이용한 방법이다.
view에서 input type='file'의 name을 이용해서 파일 정보를 받는다.
Url에서 /uploadcsvfile의 주소는 view의 uploadCSVfile 함수이다.


참고사이트: http://hanjiq.egloos.com/2373084

JQuery Form Pluginhttp://jquery.malsup.com/form/
Plugin download sitehttp://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