如何通过jQuery上传图片?
问题描述:
在过去的几天里,我一直在努力用jQuery和AJAX提交表单.我面临的问题是将图像上传到表单字段中.
For past few days i have been struggling to submit a form with jQuery and AJAX. The problem i'm facing is to upload the image in the form field.
我的表单是这样的:
<form action="#" method="GET" role="form" enctype="multipart/form-data">
<input type="text" placeholder="Name" name="name">
<input type="file" name="img" multiple>
<button type="submit">Submit </button>
</form>
和我的用于获取表单值的jQuery脚本是这样的:
and my jQuery script for getting the form value is something like this:
$("form").submit(function (event) {
$.dataArray = $(this).serializeArray(); // array of form data
console.log($.dataArray);
event.preventDefault();
});
但是,如果图像返回null,则返回除图像一以外的所有字段值.
But this returns all the field values except image one, in case of image is return null.
如何存储在数据数组中?
How do I store in the dataarray?
我想存储,以便可以通过AJAX将值发送到服务器.
I want to store so I can send the value to the server through the AJAX.
答
用于像这样上传单个图像
For uploading single image its like this
<html>
<head>
<meta charset="UTF-8">
<title>AJAX image upload with, jQuery</title>
<script type="text/javascript" src="http://ajax.googleapis.com/ajax/libs/jquery/1.12.4/jquery.min.js"></script>
<script type="text/javascript">
$(document).ready(function (e) {
$('#upload').on('click', function () {
var file_data = $('#file').prop('files')[0];
var form_data = new FormData();
form_data.append('file', file_data);
$.ajax({
url: 'http://localhost/ci/index.php/welcome/upload', // point to server-side controller method
dataType: 'text', // what to expect back from the server
cache: false,
contentType: false,
processData: false,
data: form_data,
type: 'post',
success: function (response) {
$('#msg').html(response); // display success response from the server
},
error: function (response) {
$('#msg').html(response); // display error response from the server
}
});
});
});
</script>
</head>
<body>
<p id="msg"></p>
<input type="file" id="file" name="file" multiple />
<button id="upload">Upload</button>
</body>
</html>
对于多张图片,您将不得不循环播放不同的内容
For multiple images u will have to loop its kinda different