Django 开发随笔(四)

Django与Flex

尝试使用Flex上传文件到Django端,网上有很多例子,都是使用FileReference将文件包装成一个form表单,然后使用URLRequest去提交这个表单,本来没有什么难的,但总是失败。

Flex端代码如下:

import mx.controls.Alert;
			public var file:FileReference;
			
			private function init():void{
				file = new FileReference();
				file.addEventListener(Event.SELECT, fileSelected);
				file.addEventListener(DataEvent.UPLOAD_COMPLETE_DATA, uploadDataComplete);
				file.addEventListener(Event.COMPLETE, uploadComplete);
				file.addEventListener(IOErrorEvent.IO_ERROR, handleError);
			}
			public function handleError(event:IOErrorEvent):void 
			{
				status_txt.text = 'ERROR: ' + event.toString();
			}
			public function fileSelected(event:Event):void
			{
				file = FileReference(event.target);
				status_txt.text = 'upload file: '+ file.name;
				
				var request:URLRequest = new URLRequest('http://127.0.0.1:8000/upload/');
				request.method = URLRequestMethod.POST
				request.contentType = "multipart/form-data";
				file.upload(request,'image-file');			
			}
			
			public function uploadDataComplete(event:DataEvent):void 
			{
				var result:XML = new XML(event.data);
				status_txt.text += 'Upload Data Complete';
				status_txt.text += 'RESULT: ' + result.toString();  
				status_txt.text += 'STATUS: ' + result.status;
				status_txt.text += 'MESSAGE: '+ result.message;
			}
			
			public function uploadComplete(event:Event):void 
			{
				status_txt.text += 'Upload complete';
			}
			protected function btnOpenFile_clickHandler(event:MouseEvent):void
			{
				var imageTypes:FileFilter = new FileFilter("png", "*.png");     
				var allTypes:Array = new Array(imageTypes);     
				file.browse(allTypes);  
			}

在fileSelected函数内,使用file.upload函数上传表单,其中第二个参数是表单中包含的文件名。

Django端代码:

def upload(request):
    print "running into upload file..."
    if request.method == 'POST':
        file = request.FILES['image-file']
        file_name = save_file(file)
        print "File %s was saved successfully." % file_name
        return HttpResponse(file_name)
    else:
        return HttpResponse("The method must be post.")

运行后总是得到异常“ERROR: [IOErrorEvent type="ioError" bubbles=false cancelable=false eventPhase=2 text="Error #2038"]”

后一步一步调试,发现是 csrf.CsrfViewMiddleware这个中间件的错误,这个原来是用来做跨域校验的, 后来看到csrf的process_view方法中有一段代码:

if getattr(callback, 'csrf_exempt', False):
            return None

于是给upload方法加上@csrf_except的decorate 方法,问题解决。

posted @ 2011-04-10 15:43  仨儿  阅读(486)  评论(0编辑  收藏  举报