我正在使用jQuery脚本将文件上传到新页面。它在某种程度上也有效,但问题在于它将表单数据发送为object FormData
。
以下是代码:
$('#submit').click(function () {
var formData = new FormData($(this).form);
$.ajax({
url: '/test/file_capture',
//Ajax events
beforeSend: function (e) {
alert('Are you sure you want to upload document.');
},
success: function (e) {
alert('Upload completed');
},
error: function (e) {
alert('error ' + e.message);
},
// Form data
data: formData,
//Options to tell jQuery not to process data or worry about content-type.
cache: false,
contentType: false,
processData: false
});
return false;
});
HTML部分如下:
<form enctype="multipart/form-data">
<input type="file" id="image" name="image" accept="Image/*" />
<input type="submit" id="submit" name="" value="Upload" />
</form>
但生成的链接如下:
?的http://本地主机:4965 /测试/ file_capture [对象%20FormData]安培; _ = 1386501633340
没有图像名称或附加任何其他内容。我错过了什么?即使没有错误,也会发出请求并显示上传完成警报。
答案 0 :(得分:11)
你应该只提交文件 - 而不是完整的表格
var fileInput = $('#image');
var file = fileInput.files[0];
var formData = new FormData();
formData.append('file', file);
修改强>
<script src="http://ajax.googleapis.com/ajax/libs/jquery/1.8.3/jquery.min.js"></script>
<form enctype="multipart/form-data">
<input type="file" id="image" name="image" accept="Image/*" />
<input type="submit" id="submit" name="" value="Upload" />
</form>
<script>
$('#submit').click(function (event) {
event.preventDefault()
var file = $('#image').get(0).files[0];
var formData = new FormData();
formData.append('file', file);
$.ajax({
url: '/test/file_capture',
//Ajax events
beforeSend: function (e) {
alert('Are you sure you want to upload document.');
},
success: function (e) {
alert('Upload completed');
},
error: function (e) {
alert('error ' + e.message);
},
// Form data
data: formData,
type: 'POST',
//Options to tell jQuery not to process data or worry about content-type.
cache: false,
contentType: false,
processData: false
});
return false;
});
</script>
答案 1 :(得分:7)
您需要明确获取该文件。
var image = $('#image')[0].files[0];
然后将文件追加到formData:
formData.append( image );
这是我如何做的一个例子:
var image = $('#image')[0].files[0];
if( window.FormData ) {
formdata = new FormData();
formdata.append( 'image', image );
formdata.append( 'action', 'save-image' );
$.ajax({
url: 'controller/handler',
type: 'POST',
data: formdata,
processData: false,
contentType: false,
success: function( res ) {
// Handle it.
}
});
}
}
答案 2 :(得分:0)
无法使用 GET 方法上传文件。您需要使用 POST 。
$.ajax({
method: 'POST',
url: '/test/file_capture',
// ...
另外,you need HTML 5 to be able to upload files(虽然Firefox可能允许使用早期的XHTML)。
答案 3 :(得分:0)
首先获取对象
First get the Object from HTML
//HTML
<input id = "file_name" type = "file" />
//JS
var formData = new FormData()
var file_obj = document.getElementById("file_name")
formData.append('file_name', file_obj.files[0]);
$.ajax({
url: url,
type: 'POST',
data: formData,
success: function (data) {
},
cache: false,
contentType: false,
processData: false
})