Spring boot upload picture

Keywords: network Thymeleaf Spring Database

Talking about
I always think it's very complicated to upload pictures. In addition to local upload, there are also local area network uploads and public network uploads. I can't understand them and don't want to learn them, because I always think that local upload is useless. Until today, I can see through what's not local. It's all a routine!
After the spring boot 2. X version, there is no need for any configuration when uploading, no need for any configuration files, no need to talk about anything, just do it!

Here is a demo of uploading pictures for a mall project
First, the database table

This project uses springboot, mybatis, thymeleaf
Foreground html page code

<div id="div">
		<form action="/demo/upload" method="post" enctype="multipart/form-data">
			Name of commodity on the shelf:<input class="input" type="text" name="name"><br>
			Product size:<select class="input" name="size">
			<option value="M">M</option>
			<option value="L">L</option>
			<option value="XL">XL</option>
			<option value="XXL">XXL</option>
		</select><br>
			Commodity price:<input class="input" type="text" name="price"><br>
			Quantity of goods on the shelf:<input class="input" type="text" name="number"><br>
			Product color:<select class="input" name="color">
			<option value="blue">blue</option>
			<option value="white">white</option>
			<option value="black">black</option>
			<option value="grey">grey</option>
		</select><br>
			Commodity type:<select class="input" name="kind">
			<option value="Men's wear">Men's wear</option>
			<option value="Women's wear">Women's wear</option>
			<option value="Children's wear">Children's wear</option>
			<option value="Fashion bags">Fashion bags</option>
		</select><br>
			Original price:<input class="input" type="text" name="preprice"><br>
			Product image:<input class="input" type="file" name="pic"><br>
			Listing date:<input class="input" type="date" name="time"><br>
			<input type="submit" value="Confirm the upper shelf.">
		</form>
	</div>

controller layer code

/**
 * Product image upload
 */
@RequestMapping("/upload")
    public String upload(@RequestParam(value = "pic") MultipartFile pic,@RequestParam Map param,Model model) throws ParseException {
    System.err.println("Transmitted value"+param);
    if(pic.isEmpty()){
        System.err.println("Upload file cannot be empty");
    }
    String fileName=pic.getOriginalFilename();//Get file name
    String suffixName=fileName.substring(fileName.lastIndexOf("."));//Get suffix
    System.err.println("suffixName:"+suffixName);
    String filepath="D:/tempFiles/files/";//Specify the path to which folder the picture will be uploaded
    fileName= UUID.randomUUID()+suffixName;//Rename the picture to a random name
    System.err.println("fileName:"+fileName);
    File dest=new File(filepath+fileName);//Create a file in the uploaded folder
    try {
        pic.transferTo(dest);//Write the uploaded image to disk
    } catch (IOException e) {
        e.printStackTrace();
    }
    //So far, I don't need to look at the following. It's nothing to do with uploading. It's all about entity class value passing, which is so troublesome
    Shangpin shangpin=new Shangpin();
    //I don't want to change it here. Just pass the fileName as picpath
    String picpath=fileName;
   shangpin.setPicpath(picpath);
    shangpin.setName((String) param.get("name"));
    shangpin.setSize((String) param.get("size"));
    double price=Double.parseDouble(param.get("price").toString());
    shangpin.setPrice(price);
    shangpin.setNumber(Integer.valueOf(param.get("number").toString()));
    shangpin.setColor((String) param.get("color"));
    double preprice=Double.parseDouble(param.get("preprice").toString());
    shangpin.setPreprice(preprice);
    shangpin.setKind((String) param.get("kind"));
    String sellerAccount=phone;
    shangpin.setSellerAccount(sellerAccount);
    SimpleDateFormat simpleDateFormat=new SimpleDateFormat("yyyy-MM-dd");
    shangpin.setTime(simpleDateFormat.parse((String) param.get("time")));
    int i=selectService.insertSP(shangpin);
    if(i>0){
        model.addAttribute("info","Goods uploaded successfully!");
        return "forward:getSP";
    }
    model.addAttribute("info","Product upload failed!");
    return "forward:getSP";
}

By the way, don't forget the entity class, which corresponds to the fields in the table above. You can't make any mistakes. If you make a mistake, you will make mistakes.

package com.qianlong.entity;
import java.util.Date;

public class Shangpin {
    private Integer id;
    private String name;
    private String size;
    private double price;
    private String sellerAccount;
    private int number;
    private String color;
    private double preprice;
    private String picpath;
    private Date time;
    private String kind;
    //set and get methods omitted

Ignore the service layer. Look at the dao layer, which is the mapper file

  /**
     * Goods on the shelf (upload pictures of goods)
     */
    @Insert(value = "insert into shangpin(name,size,price,sellerAccount,number,color," +
            "preprice,picpath,time,kind) values(#{name},#{size},#{price}," +
            "#{sellerAccount},#{number},#{color},#{preprice},#{picpath},#{time},#{kind})")
    int insertSP(Shangpin shangpin);

Then the upload is completed. After the upload is successful, jump to the list page and use thmeleaf to prompt the upload is successful

<!DOCTYPE html>
<html xmlns:th="www.thymeleaf.org">
	<head>
		<meta charset="utf-8" />
		<title>Commodity management</title>
		<script th:src="@{/js/jquery.1.12.4.min.js}" charset="UTF-8"></script>


	</head>
	<body>
	<a style="margin-left: 440px" href="/demo/backAddSP">Commodity shelves</a><span style="color: red;" th:text="${info}"></span>
		<table border="4">
			<thead>
			<tr>
				<th width="100px">Serial number</th>
				<th width="100px">Trade name</th>
				<th width="100px">size</th>
				<th width="100px">Price</th>
				<th width="100px">Number</th>
				<th width="100px">colour</th>
				<th width="100px">Original price</th>
				<th width="100px">Commodity type</th>
				<th width="100px">Picture path</th>
				<th width="100px">Adding time</th>
				<th width="100px">operation</th>
			</tr>
			</thead>
			<tbody>
			<!-- Traversal set, if the traversed variable userList by null Or if it does not exist, it will not traverse or report an error-->
			<tr th:each="user : ${list}">
				<!-- Set the user's primary key uId Exist in name Attribute-->
				<td width="100px" th:text="${user.id}"></td>
				<td width="100px" th:text="${user.name}"></td>
				<td width="100px" th:text="${user.size}"></td>
				<td width="100px" th:text="${user.price}"></td>
				<td width="100px" th:text="${user.number}"></td>
				<td width="100px" th:text="${user.color}"></td>
				<td width="100px" th:text="${user.preprice}"></td>
				<td width="100px" th:text="${user.kind}"></td>
				<td width="100px" th:text="${user.picpath}"></td>
				<!-- Use dates Object format date-->
				<td width="100px" th:text="${#dates.format(user.time, 'yyyy-MM-dd')}"></td>
				<td style="text-align: center" width="100px"><intput type="button" th:onclick="del([[${user.id}]]);">delete</intput></td>
			</tr>
			</tbody>
		</table>
		<script>
			function del(id) {
				alert(id);
            }
		</script>
	</body>
</html>


This is the end of the picture upload. If you have any questions, please leave a message!

Project address: link: https://pan.baidu.com/s/1DRr1Y9h0T7nvOfEL0oGvyw extraction code: w6dt

37 original articles published, 119 praised, 20000 visited+
Private letter follow

Posted by themire on Mon, 02 Mar 2020 00:04:29 -0800