我编写的脚本让用户提交带有图片的评论文字,我用ajax做了。
是 - 使用ajax上传图片。
我想扩展此scrpit并让用户上传多个文件/图片。我的代码不支持(服务器端只获得1个文件)。你可以帮我修复它,这样我就可以上传文件数组了吗?
HTML:
<form class="form-horizontal" action='#' method="post" enctype="multipart/form-data">
<input type='hidden' name='comment[pageName]' value='yard' class="pagename-field" />
<input type='hidden' name='comment[refID]' value='0' class="refid-field" />
<input type='hidden' name='allowReply' value='1' class="allowReply-field" />
<textarea class="form-control comment-field" name="comment[text]" rows="1" placeholder="כתוב/י תגובה"></textarea>
<input type='file' name='file[]' class='form-control file-field hideBox' maxlength='1' accept="image/jpg,image/png,image/jpeg,image/gif" id="uploadFile0"/>
<button class="btn btn-primary submit" >SUBMIT</button>
<img src="images/loading.gif" align="absmiddle" class="loader" id="loader">
</form>
JS:
$(function() {
$(document).on('submit','form',function(e) {
e.preventDefault();
var $form = $(this);
var act = 'add';
var file_data = $form.find('.file-field').prop('files')[0];
var form_data = new FormData();
form_data.append('act', act);
form_data.append('comment[text]', $form.find('.comment-field').val());
form_data.append('comment[pageName]', $form.find('.pagename-field').val());
form_data.append('comment[refID]', $form.find('.refid-field').val());
form_data.append('allowReply', $form.find('.allowReply-field').val());
form_data.append('feel', $form.find('.feel-field').val());
form_data.append('file[]', file_data);
$("#loader").show();
// alert(form_data);
$.ajax({
type: "POST",
url: "ajax/addComment.php",
dataType: 'text',
cache: false,
contentType: false,
processData: false,
async: false,
data: form_data,
success: function(data)
{
$("#loader").hide();
$('#commentsBox'+$form.find('.refid-field').val()).prepend(data);
$("form").reset();
}
});
return false; // avoid to execute the actual submit of the form.
});
});