form表单发送请求,参数含上传图片及其他字段

一、需求:

  1.url:http://192.168.1.5:1012/wuju-server/device/image/addDeviceNbDetail

  2.请求方式:post

  3.参数: pic :file文件(上传的图片); ycl:固定的一个id号; phones: 电环号码

二、源代码:

<html>
    <header>
        <meta charset="utf-8">
    </header>
<script type="text/javascript" src="https://cdn.staticfile.org/jquery/3.1.1/jquery.min.js"></script>

<form id="upload" enctype="multipart/form-data" method="post"> 
 <input type="file" name="file" id="pic"/> 
 <input type="text" name="ycl" id="ycl"/> 
 <input type="text" name="phones" id="phones"/> 
 <span class="showUrl"></span> 
 <img src="" class="showPic" alt=""> 
</form> 
<input type="button" value="提交" onclick="uploadPic();"/> 
<script type="text/javascript">
function uploadPic() { 
  var form = document.getElementById('upload'), 
    formData = new FormData(form); 
  $.ajax({ 
   url:"http://192.168.1.5:1012/wuju-server/device/image/addDeviceNbDetail", 
   type:"post", 
   data:formData, 
   processData:false, 
   contentType:false, 
   success:function(res){ 
    if(res){ 
     alert("上传成功!"); 
    } 
    console.log(res); 
    $("#pic").val(""); 
    $(".showUrl").html(res); 
    $(".showPic").attr("src",res); 
   }, 
   error:function(err){ 
    alert("网络连接失败,稍后重试",err); 
   } 
  
  }) 
  
 }
 </script>
 </html>

三、效果图:

 

 

原文地址:https://www.cnblogs.com/dancer0321/p/14154091.html