溫馨提示×

溫馨提示×

您好,登錄后才能下訂單哦!

密碼登錄×
登錄注冊×
其他方式登錄
點(diǎn)擊 登錄注冊 即表示同意《億速云用戶服務(wù)條款》

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

發(fā)布時(shí)間:2021-06-28 15:25:13 來源:億速云 閱讀:178 作者:chen 欄目:大數(shù)據(jù)

本篇內(nèi)容介紹了“SpringBoot怎么實(shí)現(xiàn)上傳下載”的有關(guān)知識(shí),在實(shí)際案例的操作過程中,不少人都會(huì)遇到這樣的困境,接下來就讓小編帶領(lǐng)大家學(xué)習(xí)一下如何處理這些情況吧!希望大家仔細(xì)閱讀,能夠?qū)W有所成!

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

預(yù)覽: SpringBoot怎么實(shí)現(xiàn)上傳下載

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

**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)圖: SpringBoot怎么實(shí)現(xiàn)上傳下載

標(biāo)記java文件夾為Source root resources為resources root 為了迎合SSM框架的習(xí)慣 創(chuàng)建web文件夾 SpringBoot怎么實(shí)現(xiàn)上傳下載 配置web SpringBoot怎么實(shí)現(xiàn)上傳下載

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

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) SpringBoot怎么實(shí)現(xiàn)上傳下載

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

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

C:controller包下的多個(gè)控制器

##3.數(shù)據(jù)庫設(shè)計(jì) SpringBoot怎么實(shí)現(xiàn)上傳下載

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

4.Code 首先實(shí)現(xiàn)上傳功能。實(shí)現(xiàn)思路:使用layui提供給我們的upload Element。我們上傳這個(gè)文件,限制后綴名為pdf,限制上傳文件最大2048KB等。后臺(tái)則將上傳的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 前臺(tái)上傳的文件對象
     * @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/";
            //如果目錄不存在,自動(dòng)創(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)
        {
            //打印錯(cuò)誤堆棧信息
            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文件路徑,之后做下載的時(shí)候會(huì)用到。

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.效果一覽 以上就完成了上傳功能,讓我們來看看效果

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

“SpringBoot怎么實(shí)現(xiàn)上傳下載”的內(nèi)容就介紹到這里了,感謝大家的閱讀。如果想了解更多行業(yè)相關(guān)的知識(shí)可以關(guān)注億速云網(wǎng)站,小編將為大家輸出更多高質(zhì)量的實(shí)用文章!

向AI問一下細(xì)節(jié)

免責(zé)聲明:本站發(fā)布的內(nèi)容(圖片、視頻和文字)以原創(chuàng)、轉(zhuǎn)載和分享為主,文章觀點(diǎn)不代表本網(wǎng)站立場,如果涉及侵權(quán)請聯(lián)系站長郵箱:is@yisu.com進(jìn)行舉報(bào),并提供相關(guān)證據(jù),一經(jīng)查實(shí),將立刻刪除涉嫌侵權(quán)內(nèi)容。

AI