Recently learning Springboot related knowledge, this time using Springboot to do an upload and download function to upload a legal name and the release of the year and other information, and then also can upload a PDF file (here to limit the upload suffix name can be), after uploading, click download operation, download the corresponding PDF file.

Preview:

1. Preparation editor: IDEA/eclipse/myeclipselayui document bang help: layui development using document

How to create a Springboot project using IDEA

Use use IDEA to tag resources

According to the project structure drawing:

Mark the Java folder as Source RootResources and create a Web folder for resources root to cater to the SSM framework’s conventionsConfigure the web

The detailed configuration of POM.xml and so on can be found in my project directory.

The application.properties folder in the Resources directory is the Spring-related configuration folder. GeneratorConfig is the reverse engineered configuration file in the WebApp directory Public: static resources such as JS/json/ CSS. Upload: static resources such as JS/json/ CSS

2. Architecture Design (MVC)

Model: DAO + Service + Model three packages to achieve database connection and use the database to achieve persistent storage

View: Web page rendering files such as JSP under webApp package

C: Controller Indicates multiple controllers under the package

3. Database design

There’s nothing to talk about it’s all in the picture, okay

4.Code implements the upload function first. Implementation idea: Use the Upload Element provided by Layui. We upload this file, limit the suffix to PDF, limit the maximum uploaded file size to 2048KB, etc. The background will use Java file.transferTo to input the uploaded File into the upload package.

View layer implementation :layer.jsp:

<div class="layui-form-item"> <div class="layui-input-block"> <div class="layui-upload"> <button type="button" Class ="layui-btn layui-btn-normal" id="test8"> </button> <button type="button" class="layui-btn" </button> <input type="hidden" name="fileName" id="fileName"> </div> </div>Copy the code

The above control components

layui.use(['element', 'form', 'table', 'layer', 'vip_table', 'laydate','upload'], function() { var form = layui.form, table = layui.table, layer = layui.layer, vipTable = layui.vip_table, element = layui.element, $ = layui.jquery; var laydate = layui.laydate; var upload = layui.upload; Render ({elem: '#test8',url: 'layer/upload',auto: false //,multiple: true,bindAction: '#upload',size: Accept :' file' exts:' PDF '// Upload only PDF documents,done: Function (res){console.log(res) if(res.code == 1){$('#set-add-put ') $('#set-add-put ' input[name="fileName"]').val(res.data.fileName); $('#upload').hide(); layer.msg(res.msg, { icon: 6 }); }else if(res.code==2){ layer.msg(res.msg, { icon: 5 }); }}});Copy the code

The upload was monitored above, and the returned status codes 1 (success) and 2 (failure) were processed accordingly.

The Controller layer: LayerController:

@param file File object uploaded by the front end * @return */ @requestMapping (value = "Index/layer/upload",method = RequestMethod.POST) @ResponseBody public Map<String,Object> uploadOne(HttpServletRequest request,@RequestParam("file")MultipartFile file) { Map map=new HashMap(); Try {// Upload directory address // String uploadDir = request.getSession().getServletContext().getrealPath ("upload"); String uploadDir = request.getSession().getServletContext().getRealPath("/") +"upload/"; // If the directory does not exist, automatically create a folder File dir = new File(uploadDir); if(! dir.exists()) { dir.mkdir(); } String fileName= upload.executeupload (uploadDir,file); uploadDir=uploadDir.substring(0,uploadDir.length()-1); map.put("fileName",fileName); map.put("dir",uploadDir); }catch (Exception e) {// Prints error stack information e.printStackTrace(); Return api.returnjson (2," upload failed ",map); } return api.returnjson (1," upload successful ",map); }Copy the code

Related utility classes: api.java:

package com.example.sl.layer.util; import com.example.sl.layer.model.Layer; import java.util.HashMap; import java.util.List; import java.util.Map; Public class Api {public Map<String,Object> returnJson(int code, String msg){ Map map=new HashMap(); map.put("code",code); map.put("msg",msg); return map; } public Map<String,Object> returnJson(int code, String msg, List<Map> data){ Map map=new HashMap(); map.put("code",code); map.put("msg",msg); map.put("data",data); return map; } public Map<String,Object> returnJson(int code, String msg, Map data){ Map map=new HashMap(); map.put("code",code); map.put("msg",msg); map.put("data",data); return map; } public Map<String,Object> returnJson(int code, String msg, int count,List<Layer> data){ Map map=new HashMap(); map.put("code",code); map.put("msg",msg); map.put("count",count); map.put("data",data); return map; }}Copy the code

The Upload. Java:

package com.example.sl.layer.util; import org.springframework.web.multipart.MultipartFile; import java.io.File; import java.util.UUID; // Upload a public class Upload {/** * Extract the Upload method as a public method * @param uploadDir Upload file directory * @param file Upload object * @throws Exception */ public String executeUpload(String uploadDir,MultipartFile file) throws Exception {// File suffix = file.getOriginalFilename().substring(file.getOriginalFilename().lastIndexOf(".")); String filename = uuid.randomuuid () + suffix; File serverFile = new File(uploadDir + filename); // write the uploaded file to the serverFile file.transferTo(serverFile); return filename; }}Copy the code

By the way, the data returned to the front-end is fileName fileName and dir file path, which will be used later when downloading.

Model Layer: Layer. Java entity class under Model package:

package com.example.sl.layer.model; import com.fasterxml.jackson.annotation.JsonFormat; import java.util.Date; public class Layer { private String layerId; private String layerName; private String description; @JsonFormat(pattern="yyyy",timezone="GMT+8") private Date releaseTime; @JsonFormat(pattern="yyyy",timezone="GMT+8") private Date recordTime; private String fileName; public String getLayerId() { return layerId; } public void setLayerId(String layerId) { this.layerId = layerId == null ? null : layerId.trim(); } public String getLayerName() { return layerName; } public void setLayerName(String layerName) { this.layerName = layerName == null ? null : layerName.trim(); } public String getDescription() { return description; } public void setDescription(String description) { this.description = description == null ? null : description.trim(); } public Date getReleaseTime() { return releaseTime; } @JsonFormat(pattern="yyyy",timezone="GMT+8") public void setReleaseTime(Date releaseTime) { this.releaseTime = releaseTime; } public Date getRecordTime() { return recordTime; } @JsonFormat(pattern="yyyy",timezone="GMT+8") public void setRecordTime(Date recordTime) { this.recordTime = recordTime; } public String getFileName() { return fileName; } public void setFileName(String fileName) { this.fileName = fileName == null ? null : fileName.trim(); }}Copy the code

The dao package: LayerMapper:

package com.example.sl.layer.dao;

import com.example.sl.layer.model.Layer;
import org.apache.ibatis.annotations.Param;

import java.util.Date;
import java.util.List;

public interface LayerMapper {
    int deleteByPrimaryKey(String layerId);

    int insert(Layer record);

    Layer selectByPrimaryKey(String layerId);

    List<Layer> selectAll();

    Layer selectByLayerName(String layerName);

    List<Layer> selectByDescription(String description);

    int updateByPrimaryKey(Layer record);

    List<Layer> selectByTime(@Param("time1")Date releaseTime1,@Param("time2") Date releaseTime2);
}Copy the code

The service package: LayerService:

package com.example.sl.layer.service;

import com.example.sl.layer.model.Layer;

import java.util.Date;
import java.util.List;

public interface LayerService {
    public List<Layer> findAllLayers();

    public int InsertLayer(Layer layer);

    public int deleteLayer(String layerId);

    public Layer findByLayerName(String layerName);

    public List<Layer> findByDescription(String description);

    public List<Layer> findByTime(Date time1,Date time2);
}
Copy the code

LayerServiceImpl:

package com.example.sl.layer.service; import com.example.sl.layer.dao.LayerMapper; import com.example.sl.layer.model.Layer; import org.springframework.stereotype.Service; import org.springframework.transaction.annotation.Transactional; import javax.annotation.Resource; import java.util.Date; import java.util.List; @Service("layerService") @Transactional public class LayerServiceImpl implements LayerService{ @Resource private LayerMapper layerMapper; @Override public List<Layer> findAllLayers() { return layerMapper.selectAll(); } @Override public int InsertLayer(Layer layer) { return layerMapper.insert(layer); } @Override public int deleteLayer(String layerId) { return layerMapper.deleteByPrimaryKey(layerId); } @Override public Layer findByLayerName(String layerName) { return layerMapper.selectByLayerName(layerName); } @Override public List<Layer> findByDescription(String description) { return layerMapper.selectByDescription(description); } @Override public List<Layer> findByTime(Date time1, Date time2) { return layerMapper.selectByTime(time1,time2); }}Copy the code

Jackson is used here for date parsing so there are annotations on the entity class

This completes the uploading function. Let’s take a look at the effect

Help to you give a small 💗💗 ~

Additional :SpringBoot implementation upload and download (two)

** project is only for test learning use, reject any form of commercial use, abuse and deletion. Project source Code concern public number Code In Java, reply “SpringBoot upload download “can be obtained. In addition, there are Java learning maps, data structures and algorithm data can be accessed in the background. I hope to become a fellow traveler of Java technology with you