SpringBoot實(shí)現(xiàn)上傳下載(一)

最近在學(xué)Springboot相關(guān)知識,這次用Springboot做了一個上傳下載的功能
上傳一個法律名及其發(fā)布的年份等信息,然后還要能上傳一個pdf文件(這里限制下上傳的后綴名就可以),上傳之后,點(diǎn)擊操作中的下載,下載對應(yīng)的pdf文件。

預(yù)覽:


image.png
image.png

1.前期準(zhǔn)備

編輯器:IDEA/eclipse/myeclipse
layui文檔的bang助:layui開發(fā)使用文檔

如何使用IDEA創(chuàng)建Springboot項(xiàng)目

使用使用IDEA進(jìn)行資源標(biāo)記

根據(jù)項(xiàng)目結(jié)構(gòu)圖:


image.png

標(biāo)記java文件夾為Source root
resources為resources root
為了迎合SSM框架的習(xí)慣 創(chuàng)建web文件夾


image.png

配置web


image.png

詳細(xì)的pom.xml等配置可以參見我的項(xiàng)目目錄 這里不一一展開了 主要說一下各個目錄文件夾的作用。

resources目錄下的application.properties是spring相關(guān)配置文件夾
generatorConfig是逆向工程的配置文件
webapp目錄下 public是JS/json/css等靜態(tài)資源
upload是上傳文件存放的文件夾
WEB-INF是存放jsp等渲染的網(wǎng)頁模板文件的文件夾

2.架構(gòu)設(shè)計(jì)(MVC)

image.png

Model:dao+service+model三個包實(shí)現(xiàn)數(shù)據(jù)庫連接以及使用數(shù)據(jù)庫實(shí)現(xiàn)持久化存儲

View:webapp包下的jsp等網(wǎng)頁渲染文件

C:controller包下的多個控制器

3.數(shù)據(jù)庫設(shè)計(jì)

image.png

沒什么好說的 想說的都在圖里

4.Code

首先實(shí)現(xiàn)上傳功能。實(shí)現(xiàn)思路:使用layui提供給我們的upload Element。我們上傳這個文件,限制后綴名為pdf,限制上傳文件最大2048KB等。后臺則將上傳的File文件使用java的file.transferTo錄入upload包下。

View層實(shí)現(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實(shí)體類:

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解析 所以實(shí)體類上有注解

5.效果一覽

以上就完成了上傳功能,讓我們來看看效果

上傳.gif

幫助到你了就給顆小????吧~

另附:
SpringBoot實(shí)現(xiàn)上傳下載(二)

項(xiàng)目僅供測試學(xué)習(xí)使用,拒絕任何形式的商業(yè)用途,轉(zhuǎn)侵刪。
項(xiàng)目源碼關(guān)注公眾號Code In Java,回復(fù)"SpringBoot上傳下載"即可獲取。除此之外,還有Java學(xué)習(xí)圖譜,數(shù)據(jù)結(jié)構(gòu)與算法資料等各種資料都可以在后臺獲取。
最后編輯于
?著作權(quán)歸作者所有,轉(zhuǎn)載或內(nèi)容合作請聯(lián)系作者
【社區(qū)內(nèi)容提示】社區(qū)部分內(nèi)容疑似由AI輔助生成,瀏覽時請結(jié)合常識與多方信息審慎甄別。
平臺聲明:文章內(nèi)容(如有圖片或視頻亦包括在內(nèi))由作者上傳并發(fā)布,文章內(nèi)容僅代表作者本人觀點(diǎn),簡書系信息發(fā)布平臺,僅提供信息存儲服務(wù)。

相關(guān)閱讀更多精彩內(nèi)容

  • 本文包括:1、文件上傳概述2、利用 Commons-fileupload 組件實(shí)現(xiàn)文件上傳3、核心API——Dis...
    廖少少閱讀 12,744評論 5 91
  • Spring Cloud為開發(fā)人員提供了快速構(gòu)建分布式系統(tǒng)中一些常見模式的工具(例如配置管理,服務(wù)發(fā)現(xiàn),斷路器,智...
    卡卡羅2017閱讀 136,586評論 19 139
  • Spring Boot 參考指南 介紹 轉(zhuǎn)載自:https://www.gitbook.com/book/qbgb...
    毛宇鵬閱讀 47,275評論 6 342
  • 我保持著頭幾本書的那種孤獨(dú)。我隨身帶著它。我的寫作,我始終帶著它,不論我去哪里。去巴黎,去特魯維爾?;蛘呷ゼ~約。 ...
    清清雅風(fēng)閱讀 286評論 0 1
  • 愛。太過沉重也不行,會壓得別人喘不過氣來。人人都有自尊心,不希望一味的被保護(hù)。
    文森古堡閱讀 150評論 0 1

友情鏈接更多精彩內(nèi)容