In addition to Weibo, there is also WeChat
Please pay attention
WeChat public account
Shulou
2025-01-19 Update From: SLTechnology News&Howtos shulou NAV: SLTechnology News&Howtos > Internet Technology >
Share
Shulou(Shulou.com)06/02 Report--
This article introduces the relevant knowledge of "how to upload and download SpringBoot". In the operation of actual cases, many people will encounter such a dilemma, so let the editor lead you to learn how to deal with these situations. I hope you can read it carefully and be able to achieve something!
Recently, I am learning the relevant knowledge of Springboot. This time, I use Springboot to do an upload and download function to upload a legal name and the year in which it was released, and then upload a pdf file (the suffix name is limited here). After uploading, click download in the operation to download the corresponding pdf file.
Preview:
* * 1. Pre-preparation * * editor: bang assistance for IDEA/eclipse/myeclipse layui documents: layui development and usage documents
How to create a Springboot project using IDEA
Using IDEA for resource tagging
According to the project structure diagram:
Mark java folder as Source root resources as resources root to cater to the habit of creating web folders to cater to the SSM framework configure web
Detailed configuration such as pom.xml can be seen in my project directory here one by one to talk about the role of each directory folder.
The application.properties under the resources directory is the spring-related configuration folder generatorConfig is the reverse engineering configuration file under the webapp directory public is the static resource such as JS/json/css upload is the folder for uploading files WEB-INF is the folder for jsp and other rendered web page template files
two。 Architecture Design (MVC)
Three packages of Model:dao+service+model realize database connection and persistent storage using database.
Jsp and other web page rendering files under the View:webapp package
Multiple controllers under C:controller package
# # 3. Database design
There's nothing to say. Everything you want to say is in the picture.
4.Code first implements the upload function. Implementation idea: use the upload Element provided to us by layui. We upload this file, limit the suffix to pdf, limit the maximum 2048KB of uploading files, and so on. In the background, the uploaded File file is entered into the upload package using java's file.transferTo.
View layer implementation: layer.jsp:
Select a file to start uploading
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 / / upload upload.render ({elem:'# test8', url: 'layer/upload', auto: false / /, multiple: true, bindAction:' # upload', size: 2048 / / maximum allowed file size for upload is 2m) Accept: 'file' / / allowed file types. Exts:'pdf'// only uploads pdf documents. Done: function (res) {console.log (res) if (res.code = = 1) {/ / successful callback / / do something (such as saving the image link returned by res to the hidden field of the form) $('# 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});})
The above listens to the upload, and handles the returned status codes 1 (success) and 2 (failure) accordingly.
Controller layer: LayerController:
/ * handle file upload method request * @ param file the file object uploaded from the foreground * @ return * / @ RequestMapping (value = "Index/layer/upload", method = RequestMethod.POST) @ ResponseBody public Map 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 ();} / / call upload method String fileName=upload.executeUpload (uploadDir,file); uploadDir=uploadDir.substring (0dr. Length ()-1); map.put ("fileName", fileName); map.put ("dir", uploadDir) } catch (Exception e) {/ / print error stack information e.printStackTrace (); return api.returnJson (2, upload failed, map);} return api.returnJson (1, upload success, map);}
Related tool 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;// interface / / code=1 success 2 fail 3 warningpublic class Api {public Map returnJson (int code, String msg) {Map map=new HashMap (); map.put ("code", code); map.put ("msg", msg); return map } public Map returnJson (int code, String msg, List data) {Map map=new HashMap (); map.put ("code", code); map.put ("msg", msg); map.put ("data", data); return map;} public Map 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 returnJson (int code, String msg, int count,List data) {Map map=new HashMap (); map.put ("code", code); map.put ("msg", msg); map.put ("count", count); map.put ("data", data) Return map;}}
Upload.java:
Package com.example.sl.layer.util;import org.springframework.web.multipart.MultipartFile;import java.io.File;import java.util.UUID / / upload public class Upload {/ * extract upload method is the public method * @ param uploadDir upload file directory * @ param file upload object * @ throws Exception * / public String executeUpload (String uploadDir,MultipartFile file) throws Exception {/ / file suffix String suffix = file.getOriginalFilename () .substring (file.getOriginalFilename (). LastIndexOf (".")) / / upload file name String filename = UUID.randomUUID () + suffix; / / the file object saved on the server side File serverFile = new File (uploadDir + filename); / / write the uploaded file to file.transferTo (serverFile) in the server side file; return filename;}}
By the way, the data returned to the front end here are: fileName file name and dir file path, which will be used for download later.
Model layer: Layer.java entity classes under the 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 ();}}
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 selectAll (); Layer selectByLayerName (String layerName); List selectByDescription (String description); int updateByPrimaryKey (Layer record) List selectByTime (@ Param ("time1") Date releaseTime1,@Param ("time2") Date releaseTime2);}
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 findAllLayers (); public int InsertLayer (Layer layer); public int deleteLayer (String layerId); public Layer findByLayerName (String layerName); public List findByDescription (String description); public List findByTime (Date time1,Date time2);}
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") @ Transactionalpublic class LayerServiceImpl implements LayerService {@ Resource private LayerMapper layerMapper; @ Override public List 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 findByDescription (String description) {return layerMapper.selectByDescription (description) @ Override public List findByTime (Date time1, Date time2) {return layerMapper.selectByTime (time1,time2);}}
Jackson is used for date parsing here, so there are annotations on the entity class.
5. The upload function is completed at a glance of the results. Let's take a look at the results.
That's all for the content of "how to upload and download SpringBoot". Thank you for reading. If you want to know more about the industry, you can follow the website, the editor will output more high-quality practical articles for you!
Welcome to subscribe "Shulou Technology Information " to get latest news, interesting things and hot topics in the IT industry, and controls the hottest and latest Internet news, technology news and IT industry trends.
Views: 0
*The comments in the above article only represent the author's personal views and do not represent the views and positions of this website. If you have more insights, please feel free to contribute and share.
Continue with the installation of the previous hadoop.First, install zookooper1. Decompress zookoope
"Every 5-10 years, there's a rare product, a really special, very unusual product that's the most un
@ WebServlet (name = "httpServletDemo", urlPatterns = "/ httpServletDemo", initParams = {
© 2024 shulou.com SLNews company. All rights reserved.