2013-08-20 15 views
0

我有一個非常簡單的網頁,使用戶能夠從他們的操作系統選擇一個文件,「提交」到一個服務器上運行node.js中如何使用jQuery發佈文件提交?

我現在在更新前端使用jQuery,這樣我可以保持相同的頁面上的用戶,然後做一些與服務器的響應有用的過程。

我加入jQuery代碼as per this answer here,但這樣做已經改變了服務器的實際找到(使用)傳遞文件的能力。

是否有一些具體的事情我需要添加在張貼文件時?

相關HTML:

<form id="upload" enctype="multipart/form-data" 
    action="http://localhost:3000/file_upload" method ="post"> 
     <div> 
      <label for="pickedFile">Upload CSV: </label><input type="file" name="pickedfile" id = "pickedfile"/> 
     </div> 

     <div> 
      <button>Send the file</button> 
     </div> 
</form> 
<script src="js/app.js"></script> 

相關app.js摘錄如下:

// site/js/app.js 

var app = app || {}; 

(function($){ 


})(jQuery); 

$(function(){ 
    $("form").submit(function(){ 
    $.post($(this).attr("action"), $(this).serialize(), function(jsonData){ 
     console.log(jsonData); 
    }, "json"); 
    return false; 
    }); 
}); 

相關服務器片斷如下:

var app = express(); 

//need to configure this before setting up the routes 
//if you want file passing to work correctly 
app.configure(function(){ 
    app.use(express.bodyParser()); 
    app.use(app.router); 
}); 
app.post('/file_upload', function(req, res) { 
    //file should be in req.files.pickedfile 

    // get the temporary location of the file 
    // When using jquery, pickedfile is undefined! 
    var tmp_path = req.files.pickedfile.path; 
}); 

回答

1

你的快遞部分似乎是很好,但是jQuery代碼需要一個插件,如 jQuery.Form,它處理多部分形式提交:

$("form").ajaxForm({ 
    data: { 
    extraParam: "foobar" 
    }, 
    error: function() { 
    alert("Uh oh, something went wrong"); 
    }, 
    success: function(response) { 
    alert("Upload completed!"); 
    console.log(response); 
    } 
}); 
+0

我已經使用[此小插件(https://github.com/jfeldstein/jQuery.AjaxFileUpload.js/blob/master/README)並很高興與它。我的用例要求我在選擇文件後立即自動發送multipart表單。 – Plato

+0

所以我現在有jQuery.Form工作(文件上傳),但成功和錯誤回調觸發。我必須改變一些關於服務器的響應來讓jQuery確認它嗎? –

+0

不是。服務器已經返回上傳的東西了嗎?如果Express返回'204 No Content',瀏覽器可能不會對響應做任何事情,或者如果您將響應設置爲JSON,但返回無效的JSON,則jQuery可能會失敗。 – gustavohenke