4

这是我的 phonegapfile 文件:该文件正在向 django 服务器发送数据,但我无法将文件存储在服务器中。用于捕获和存储文件的 python 视图函数是什么?

<!DOCTYPE HTML>
<html>
<head>
<title>File Transfer Example</title>

<script type="text/javascript" charset="utf-8" src="cordova-2.5.0.js"></script>
<script type="text/javascript" charset="utf-8">

// Wait for Cordova to load
//
document.addEventListener("deviceready", onDeviceReady, false);

// Cordova is ready
//
function onDeviceReady() {

    // Retrieve image file location from specified source
navigator.camera.getPicture(uploadPhoto,
function(message) {
    alert('get picture failed');},
    { quality: 50, 
    destinationType: navigator.camera.DestinationType.FILE_URI,
    sourceType: navigator.camera.PictureSourceType.PHOTOLIBRARY }
);

}

function uploadPhoto(imageURI) {
    var options = new FileUploadOptions();
    options.fileKey="file";
    options.fileName=imageURI.substr(imageURI.lastIndexOf('/')+1);
    options.mimeType="image/jpeg";

    var params = {};
    params.value1 = "test";
    params.value2 = "param";

    options.params = params;

    var ft = new FileTransfer();
    ft.upload(imageURI, encodeURI("http://something.com/uploadphonegapfil/"),win,fail,options);
}

function win(r) {
    console.log("Code = " + r.responseCode);
    console.log("Response = " + r.response);
    console.log("Sent = " + r.bytesSent);
}

function fail(error) {
    alert("An error has occurred: Code = " + error.code);
    console.log("upload error source " + error.source);
    console.log("upload error target " + error.target);
}
</script>
</head>
<body>
<h1>Example</h1>
<p>Upload File</p>
</body>
</html>

视图.py

@csrf_exempt

def uploadPhonegapFile(request):
    print "-------- hitting the url"
    to_json={}
    return HttpResponse(simplejson.dumps(to_json), mimetype= 'application/json')

那个上传请求到达了服务器,我得到了打印“-----------------hitting the url” 那么我怎样才能在这里捕获文件呢?或者有没有办法将文件存储在我的服务器文件夹中?

4

1 回答 1

3

如果您使用 JQuery 使用 POST 将文件发送到服务器,而不是request.FILES['file']使用request.POST[].

if request.method == 'POST':
    filename=request.FILES['file']
    form = SomeForm(request.POST, request.FILES)
    if form.is_valid():
        dest_file = open('C:/system/upload/'+ str(filename), 'wb+')
        path = 'C:/system/upload/upload/'+ str(filename)
        for chunk in  request.FILES['file'].chunks():
            dest_file.write(chunk)
        dest_file.close()
于 2013-04-25T10:12:25.940 回答