最近在學(xué)Springboot相關(guān)知識拼岳,這次用Springboot做了一個上傳下載的功能
上傳一個法律名及其發(fā)布的年份等信息炉菲,然后還要能上傳一個pdf文件(這里限制下上傳的后綴名就可以),上傳之后舶替,點擊操作中的下載,下載對應(yīng)的pdf文件。
預(yù)覽:
1.前期準(zhǔn)備
編輯器:IDEA/eclipse/myeclipse
layui文檔的bang助:layui開發(fā)使用文檔
如何使用IDEA創(chuàng)建Springboot項目
根據(jù)項目結(jié)構(gòu)圖:
標(biāo)記java文件夾為Source root
resources為resources root
為了迎合SSM框架的習(xí)慣 創(chuàng)建web文件夾
配置web
詳細(xì)的pom.xml等配置可以參見我的項目目錄 這里不一一展開了 主要說一下各個目錄文件夾的作用氛堕。
resources目錄下的application.properties是spring相關(guān)配置文件夾
generatorConfig是逆向工程的配置文件
webapp目錄下 public是JS/json/css等靜態(tài)資源
upload是上傳文件存放的文件夾
WEB-INF是存放jsp等渲染的網(wǎng)頁模板文件的文件夾
2.架構(gòu)設(shè)計(MVC)
Model:dao+service+model三個包實現(xiàn)數(shù)據(jù)庫連接以及使用數(shù)據(jù)庫實現(xiàn)持久化存儲
View:webapp包下的jsp等網(wǎng)頁渲染文件
C:controller包下的多個控制器
3.數(shù)據(jù)庫設(shè)計
沒什么好說的 想說的都在圖里
4.Code
首先實現(xiàn)上傳功能。實現(xiàn)思路:使用layui提供給我們的upload Element野蝇。我們上傳這個文件讼稚,限制后綴名為pdf,限制上傳文件最大2048KB等绕沈。后臺則將上傳的File文件使用java的file.transferTo錄入upload包下锐想。
View層實現(xiàn):
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" id="upload">開始上傳</button>
<input type="hidden" name="fileName" id="fileName">
</div>
</div>
</div>
以上控件組件
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.render({
elem: '#test8'
,url: 'layer/upload'
,auto: false
//,multiple: true
,bindAction: '#upload'
,size: 2048 //最大允許上傳的文件大小 2M
,accept: 'file' //允許上傳的文件類型
,exts:'pdf'//只上傳pdf文檔
,done: function(res){
console.log(res)
if(res.code == 1){//成功的回調(diào)
//do something (比如將res返回的圖片鏈接保存到表單的隱藏域)
$('#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
});
}
}
});
以上對upload的監(jiān)聽,并且對返回的狀態(tài)碼1(成功),2(失敗)做相應(yīng)處理乍狐。
Controller層:
LayerController:
/**
* 處理上傳文件方法請求
* @param file 前臺上傳的文件對象
* @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 {
//上傳目錄地址
// String uploadDir = request.getSession().getServletContext().getRealPath("upload");
String uploadDir = request.getSession().getServletContext().getRealPath("/") +"upload/";
//如果目錄不存在赠摇,自動創(chuàng)建文件夾
File dir = new File(uploadDir);
if(!dir.exists())
{
dir.mkdir();
}
//調(diào)用上傳方法
String fileName=upload.executeUpload(uploadDir,file);
uploadDir=uploadDir.substring(0,uploadDir.length()-1);
map.put("fileName",fileName);
map.put("dir",uploadDir);
}catch (Exception e)
{
//打印錯誤堆棧信息
e.printStackTrace();
return api.returnJson(2,"上傳失敗",map);
}
return api.returnJson(1,"上傳成功",map);
}
相關(guān)的工具類:
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;
//接口
//code=1 success 2 fail 3 warning
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;
}
}
Upload.java:
package com.example.sl.layer.util;
import org.springframework.web.multipart.MultipartFile;
import java.io.File;
import java.util.UUID;
//上傳
public class Upload {
/**
* 提取上傳方法為公共方法
* @param uploadDir 上傳文件目錄
* @param file 上傳對象
* @throws Exception
*/
public String executeUpload(String uploadDir,MultipartFile file) throws Exception
{
//文件后綴名
String suffix = file.getOriginalFilename().substring(file.getOriginalFilename().lastIndexOf("."));
//上傳文件名
String filename = UUID.randomUUID() + suffix;
//服務(wù)器端保存的文件對象
File serverFile = new File(uploadDir + filename);
//將上傳的文件寫入到服務(wù)器端文件內(nèi)
file.transferTo(serverFile);
return filename;
}
}
順帶一提,這里返回給前端的數(shù)據(jù)有:fileName文件名還有dir文件路徑澜躺,之后做下載的時候會用到蝉稳。
Model層:
model包下的Layer.java實體類:
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包: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);
}
service包:
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);
}
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);
}
}
這里使用了jackson作date解析 所以實體類上有注解
5.效果一覽
以上就完成了上傳功能,讓我們來看看效果
幫助到你了就給顆小????吧~