繁体   English   中英

使用javascript上传带有其他参数的图像作为JSON类型

[英]upload an image with other parameters as JSON type using javascript

我有一个包含参数的对象。 我想将图像上传到服务器,但仅使用javascript。 我怎样才能做到这一点?

<input id="imgItem" type="file" class="form-control">
<input type="text" id="title">
<input type="text" id="description">
<button onclick="handle();">
<script>
function handle(){
   var params={
   title:document.getElementById('title').value,
   desc: document.getElementById('description').value,
   img://i don't know what I must do,
   };
   postItem(params, function(data){
    alert(JSON.stringify(data));
   });

}
function postItem(param, callbackFunction){
   $.ajax({
   url:myUrl,
   data:param,
   type:'POST',
   contentType:'application/x-www-form-urlencoded',
   xhrFields:{withCredentials: false},
   success: function(response){
   callbackFunction(response);
   }
 });
}
</script>

您可以使用FormData

var data = new FormData();

data.append('title', document.getElementById('title').value);
data.append('desc', document.getElementById('description').value);

$("input[type='file']").each(function (index) {
    try {
        data.append($(this).attr('name'), $(this)[0].files[0], $(this).attr('name'));
    } catch (ignore) {}
});

$.ajax({
    method: 'POST',
    url: url,
    data: data,
    cache: false,
    contentType: false,
    processData: false
}).done(function () {
    //your code here
}).fail(function (xhr, status, error) {
    //your code here
}).always(function () {
    //your code here
});

或将其用作常规表单提交,并在Submit事件中填写标题和描述值。

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM