Spring Boot+vue. Js + AXIos file today, fortunately the most successful, here to make a detailed note!

Spring Boot+vue.js+ AXIos file upload

Two tables, file table and product table, when uploading, in the product table to save the ID of the file table, file table to save the name of the file, path and other information. The table structure is as follows:

Product list: Product

File table: product_doc

### Front-end interface

<! --@author: An_Zhongqi--> <div th:fragment="html"> <script> $(function () { var time = new Date(); var nowTime = time.toLocaleString(); Var data4Vue = {/** * file indicates the attachment to upload */ URI: 'topublish', result: [], Component: {id: 0, name: 'category: {'id': 0}, }, categorys: [], categoryy: {id: 0, name: ''}, file:null, }; //ViewModel var vue = new Vue({ el: '#workingArea', data: data4Vue, mounted: function () { linkDefaultActions(); }, methods: { publish: Special character checking function () {/ / var regEn drive = new RegExp (" [` ~! @ # $^ & * () = | {} ':', \ \ [\ \] < > /? ~! @ # $... & * () - | {} 【 】 '; : "" '.,,? "); If (0 = = this.com ponent. Name. Length) {$(" span. ErrorMessage "). The HTML (" please enter the member name "); $("div.registerErrorMessageDiv").css("visibility", "visible"); return; Var formData = new formData (); var url = this.uri; formData.append("doc", this.file); formData.append("name", this.component.name); Function (response) {var a=$("#categoryDoc").val(" "); console.log(a) vue.file = null; $("#singlePic").val(''); vue.singleFile = null; vue.component= { id: 0, name: '', category: {'id': 0} }; var result = response.data; console.log(response.data.code); if (result.code == 0) { location.href = "publishSuccess"; } else { $("span.errorMessage").html(result.message); $("div.registerErrorMessageDiv").css("visibility", "visible"); }}); }, /** * When a local file is selected by the upload control, the file object will be saved on data4vue.file * @param event */ getFile: function (event) { this.file = event.target.files[0]; }}}); }) </script> <title> <div class="panel panel-primary"> <div class="panel-heading"> <h3 Class ="panel-title"> </h3> </div> <div class="panel-body"> class="registerErrorMessageDiv"> <div class="alert alert-danger" role="alert"> <button type="button" class="close" data-dismiss="alert" aria-label="Close"></button> <span class="errorMessage"></span> </div> </div> <div style="width: 70%; float: Left "horizontal"> <div class="form-group"> <label class=" col-SM-5 control-label"> Component name </label> <div Class ="col-sm-5"> <input V-model ="component.name" type="text" class="form-control" placeholder=" placeholder "> </div> <div class="form-group"> <label class="col-sm-5 control-label"> upload file </label> <div class="col-sm-5 custom-file"> <! <input ID ="categoryDoc" Accept ="application/ Msword "type="file" name="doc" @change="getFile($event)" th:placeholder=" placeholder "/> <p class="help-block"> </p> </div> </div> <div <div class="col-sm-offset "> < form type=" publish" @click="publish" id=" BTN "value=" publish" class="btn btn-primary"> </div> </div> </div> </div> </div> </div>Copy the code

### Entity class (product.java)

package com.jeemia.component.pojo; import com.fasterxml.jackson.annotation.JsonFormat; import com.fasterxml.jackson.annotation.JsonIgnoreProperties; import org.springframework.data.elasticsearch.annotations.Document; import javax.persistence.*; import java.util.Date; import java.util.List; /** * @program: component * @author: An_Zhongqi **/ @Entity @Table(name = "product") @JsonIgnoreProperties({"handler", "hibernateLazyInitializer"}) @Document(indexName = "component", type = "product") public class Product { @Id @GeneratedValue(strategy = GenerationType.IDENTITY) @Column(name = "id") int id; @ManyToOne @JoinColumn(name = "cid") private Category category; @ManyToOne @JoinColumn(name = "uid") private User user; /** * primary key association, ALL->ALL cascade/Add/update/Delete */ @oneToOne (cascade = cascadeType.all) @joinColumn (name = "docid") private ProductDoc productDoc; Private String name; private String name; private String name; private String name; private String name; @Transient private ProductImage firstProductImage; @Transient private List<ProductImage> productSingleImages; @Transient private List<ProductImage> productDetailImages; @Transient private int reviewCount; @Transient private int saleCount; public int getId() { return id; } public void setId(int id) { this.id = id; } public Category getCategory() { return category; } public void setCategory(Category category) { this.category = category; } public User getUser() { return user; } public void setUser(User user) { this.user = user; } public String getName() { return name; } public void setName(String name) { this.name = name; } public ProductDoc getProductDoc() { return productDoc; } public void setProductDoc(ProductDoc productDoc) { this.productDoc = productDoc; }}Copy the code

Entity class (ProductDoc)

package com.jeemia.component.pojo; import com.fasterxml.jackson.annotation.JsonBackReference; import com.fasterxml.jackson.annotation.JsonIgnoreProperties; import javax.persistence.*; import java.util.List; /** * @author: An_Zhongqi * @description: 2019/4/24 15:11 */ @Entity @Table(name = "product_doc") @JsonIgnoreProperties({ "handler","hibernateLazyInitializer"}) public class ProductDoc { @Id @GeneratedValue(strategy = GenerationType.IDENTITY) @Column(name = "id") private int id; public String name; private Float size; // File path private String Folder; public int getId() { return id; } public void setId(int id) { this.id = id; } public String getName() { return name; } public void setName(String name) { this.name = name; } public Float getSize() { return size; } public void setSize(Float size) { this.size = size; } public String getFolder() { return folder; } public void setFolder(String folder) { this.folder = folder; }}Copy the code

###Service(ProductService.java)

package com.jeemia.component.service; import com.jeemia.component.dao.ProductDAO; import com.jeemia.component.pojo.Category; import com.jeemia.component.pojo.Product; import com.jeemia.component.util.Page4Navigator; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.data.domain.Page; import org.springframework.data.domain.PageRequest; import org.springframework.data.domain.Pageable; import org.springframework.data.domain.Sort; import org.springframework.stereotype.Service; import java.beans.PropertyDescriptor; import java.util.ArrayList; import java.util.List; /** * @program: component * @author: An_Zhongqi **/ @Service public class ProductService { @Autowired ProductDAO productDAO; @Autowired CategoryService categoryService; @Autowired ProductImageService productImageService; @Autowired OrderItemService orderItemService; @Autowired ReviewService reviewService; /** * add data */ public void add(Product bean) {productDao.save (bean); } public void delete(Product id) { productDAO.delete(id); } public void updata(Product bean) { productDAO.save(bean); } public Product get(int id) { return productDAO.findById(id).orElse(null); } public Page4Navigator<Product> list(int cid, int start, int size, int navigatePages) { Category category = categoryService.get(cid); Sort sort = new Sort(Sort.Direction.DESC, "id"); Pageable pageable = new PageRequest(start, size, sort); Page<Product> pageFromJPA = productDAO.findByCategory(category, pageable); return new Page4Navigator<>(pageFromJPA, navigatePages); }}Copy the code

###Controller()

/** * publish * @param product * @param productDoc * @param session * @param doc * @param model * @param request * @return * @throws Exception */ @PostMapping("/topublish") public Object publish(Product product, ProductDoc productDoc, ProductImage productImage, HttpSession session, MultipartFile doc, Model model, HttpServletRequest request) throws Exception { User user = (User) session.getAttribute("user"); String filename = doc.getOriginalFilename(); Long size1 = doc.getSize() / 1024; Float size = (float) size1; File fileFolder = new File(request.getServletContext().getRealPath("file/product")); String pictureFolder = iamgeFolder.toString(); String folder = fileFolder.toString(); product.setUser(user); product.setProductDoc(productDoc); product.setProductImage(productImage); product.setCreateDate(new Date()); productService.add(product); saveOrUpdateDocFile(product, doc, request, model); productDoc.setName(filename); productDoc.setSize(size); productDoc.setFolder(folder); productDosService.add(productDoc); return Result.success(); } /** * @param request * @param model * @throws IOException */ public void saveOrUpdateDocFile(Product bean, MultipartFile doc, HttpServletRequest request, Model Model) throws IOException {// File fileFolder = new File(request.getServletContext().getRealPath("file/product")); String Filename = doc.getoriginalfilename (); File filename = new File(fileFolder, Filename); // Create if (! filename.getParentFile().exists()) { filename.getParentFile().mkdirs(); } // Save the file doc.transferto (filename); // Put the Filename in model for subsequent display with model.addattribute ("Filename", Filename); }Copy the code