Home > Web Front-end > JS Tutorial > body text

Ajax-based formData image and data upload rue implementation

php中世界最好的语言
Release: 2018-03-31 16:21:17
Original
2012 people have browsed it

This time I will bring you the Ajax-based formData image and data upload rue implementation, Ajax-based formData image and data upload What are the precautions , the following is a practical case, let's take a look.

I recently worked on a project about user data and form uploading, and encountered a lot of pitfalls. I will share the summary here with you, hoping to help everyone. (Xiaobai, everyone is welcome to communicate more)

I won’t go into too much detail, just come to the code! !

1. Upload componentExplain that the project is based on the vue framework

<template>
  <p class="newproduct">    
    <p class="topbox">
       <p class="shopbox">     
        <img class="shopicon" src="../../assets/head.jpg">
        <p class="shopname">开心就好的小店</p>
      </p>
    </p>
    <p class="goodsbox">
      <p class="startleft namebox">
        <label class="title">商品名称:</label><input class="noborder" v-model="goodsname" placeholder="请输入商品名称">
      </p>
      <p class="startleft goodstypebox">
        <label class="title">商品类型:</label>
        <select v-model="goodstype">
          <option value="请选择">请选择</option>
          <option value="图书">图书</option>
          <option value="卡券">卡券</option>
          <option value="服装">服装</option>
          <option value="礼品">礼品</option>
          <option value="运动装备">运动装备</option>
          <option value="电子设备">电子设备</option>
          <option value="日用百货">日用百货</option>
          <option value="其他">其他</option>
        </select>
      </p>      
      <p class="startleft describebox">
        <label class="title">商品描述</label>       
      </p class="startleft">
       <textarea class="describeinfo" v-model="goodsinfo"></textarea>
      <p class="startleft">
        <label class="title">单价:</label>
        <input class="noborder" placeholder="请输入单价" v-model="price">
      </p>
      <p class="startleft">
        <label class="title">数量:</label>
        <input class="noborder" placeholder="请输入数量" v-model="number">
      </p>
      <p class="startleft">
        <label class="title">联系电话:</label>
        <input class="noborder" placeholder="请输入手机号" v-model="phone">
      </p>
      <p class="startleft">
        <label class="title">地址:</label>
        <input class="noborder" placeholder="请输入地址" v-model="address">
      </p>
      <p class="startleft">
        <label class="title">图片</label>
        <img src="">
        <img src="">      
      </p>      
      <p class="addimg">
        <p class="imgbox">
          <img class="goodsimg" src="../../assets/addimg.png">
          <input id="file" type="file" class="fileupload" accept="image/*" multiple capture="camera" @change="viewimg()"/>
        </p>
        <p class="imgbox">
          <img class="goodsimg" src="../../assets/addimg.png">
          <input type="file" class="fileupload" accept="image/*" capture="camera" @change="viewimg()"/>
        </p> 
      </p>
    </p>
    <p class="bottombox" :style="{&#39;top&#39;:(height-12) + &#39;px&#39;}">
      <ul class="bottommenu">
        <li class="item" @click="backHome()">首页</li>
        <li class="item" @click="backShop()">返回货架</li>
        <li class="item border">放弃编辑</li>
        <li class="item" @click="uploadtest()">上架</li>
      </ul>
    </p>
    <p class="fillbottom"></p>
  </p>
</template>
Copy after login

Instructions, including two components for uploading images, the first one has multiple for multi-file mode , that is, multiple pictures can be selected at one time, followed by single file mode.

2. Next is the preview of the picture

viewimg($event) {
  //获取当前的input标签
  var currentObj = event.currentTarget; 
  //找到要预览的图片img标签,亦可动态生成
  var img = currentObj.parentNode.children[0]; 
  setImagePreview(currentObj, img);
  function setImagePreview(docObj, imgObjPreview) {
    if (docObj.files && docObj.files[0]) {
      imgObjPreview.style.display = 'block';
      imgObjPreview.src = window.URL.createObjectURL(docObj.files[0]);
    }
  }
}
Copy after login

The main function of this part is to display the selected picture. Of course, there are not multiple pictures here. Situation

3. Core part, image upload

/*采用formData形式上传图片和表单数据*/
upload: function() {
  var _self = this;
  var formData = new FormData();
  var inputs = $("input.fileupload");
  for (var i = 0; i < inputs.length; i++) {
    var file = inputs[i];
    if (inputs[i].files[0]) {
      formData.append("file", file.files[0], file.files[0].name);
    }
  }
  formData.append('barterCommodityname', _self.goodsname);
  formData.append('barterSellingprice', _self.price);
  formData.append('barterContactinformation', _self.phone);
  formData.append('barterCommodityquantity', _self.number);
  formData.append('barterCommodityaddress', _self.address);
  formData.append('barterDescriptioninform', _self.goodsinfo);
  formData.append('barterCategoryid', _self.goodstype);
  var _self = this;
  $.ajax({
    type: 'POST',
    url: 'http://10.145.0.05/goods/addGoods',
    dataType: "json",
    data: formData,
    processData: false,
    contentType: false,
    success: function(data) {
      console.log(data);
      if (data.code == 200) {
        console.log("success");
        // _self.$router.push('/');
      } else {
        alert(data.message);
      }
    }
  });
}
Copy after login

Description:

Similar to formData.append('barterCategoryid', _self.goodstype) ; is a form of key-value pairs to save data, and formData.append(“file”, file.files[0], file.files[0].name); The first parameter is the parameter name received by the server, The second parameter is the file object, and the third parameter is the file name, so that multiple files can be added to the server in the form of an array.

When the backend receives this type of file, the type is specified as: MultipartFile type

Special instructions:

processData: false,
contentType: false,

These two sentences must be added, otherwise the data will be serialized and the backend cannot recognize it

I believe you have mastered it after reading the case in this article Method, for more exciting information, please pay attention to other related articles on the php Chinese website!

Recommended reading:

How to configure Google Chrome to support AJAX requests of the file protocol

How to use php to receive ajax submissions Data to the background

The above is the detailed content of Ajax-based formData image and data upload rue implementation. For more information, please follow other related articles on the PHP Chinese website!

Related labels:
source:php.cn
Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template
About us Disclaimer Sitemap
php.cn:Public welfare online PHP training,Help PHP learners grow quickly!