Spring Boot+Layui文件上传以及下载

文件上传

前端页面:

<div class="layui-upload">
    <form method="post" id="sourceupload">
        <div style="padding-left: 50px;margin-bottom: 5px;">
            <button type="button" class="layui-btn layui-btn-normal" id="choose">选择文件</button>
            <button type="button" class="layui-btn" id="upload">开始上传</button>

        </div>
    </form>
</div>

js文件:

layui.use('upload', function(){
    var $ = layui.jquery
        ,upload = layui.upload;
upload.render({
    elem: '#choose'
    ,url: '/document/upload' //上传接口
    ,data:{
        id:function () {
            return $('#id').val();
        }
    }
    ,auto: false
    ,accept: 'file'
    ,size: 307200
    ,method: 'POST'
    //,multiple: true
    ,bindAction: '#uplaod'
    ,done: function(res){
        // test1();
        layer.msg('上传成功');
        console.log(res)
    }
});
});

文件实体类:

@Data
public class DocumentFile {
    private Integer id;
    private String name;
    private String path;
    private Date time;
}

controller层:

  //上传文件
    @PostMapping("document/upload")
    @ResponseBody
    public String upload(@RequestParam("file") MultipartFile file, String id){
        System.out.println(file);
        String pathString=null;
        if(file!=null){
            pathString="D:/upload/"+file.getOriginalFilename();
            //将上传的文件信息写入数据库
            DocumentFile documentFile=new DocumentFile();
            documentFile.setName(file.getOriginalFilename());
            documentFile.setPath(pathString);
            documentFile.setTime(new Timestamp(new Date().getTime()));
            documentService.addDocumentFile(documentFile);

        }
        try {
            File files = new File(pathString);
            System.out.println(pathString);
            if(!files.getParentFile().exists()){
                files.getParentFile().mkdirs();
            }
            file.transferTo(files);
        } catch (IOException e) {
            e.printStackTrace();
        }
        return "{\"code\":0,\"msg\":\""+pathString+"\"}";
    }

server层:

    public void addDocumentFile(DocumentFile documentFile){
        documentDao.addDocumentFile(documentFile);     
    }

dao层:

void addDocumentFile(DocumentFile documentFile);

xml文件:

 <select id="addDocumentFile" parameterType="DocumentFile">
        insert into [document_file] ([name],path,time)
        values(#{name},#{path},#{time})
    </select>

文件下载:

前端页面:

<button type='button' class='layui-btn  layui-btn-xs' onclick='download("传对应文件的id值")'>下载</button>

js文件

//下载文件
function download(id) {
    var link = document.createElement('a');
    link.href = "document/down?id=" + id;
    link.click();
}

controller层:

@RequestMapping(value="/down", produces = {"application/text;charset=UTF-8"})
    @ResponseBody
    public String down(HttpServletResponse response, Integer id){
        try {
            //根据文件id查询文件路径
            String filePath = documentService.getFilePath(id);
            //根据文件路径下载文件信息
            FileUtil.down(response, filePath);
            response.setContentType("text/html;charset=utf-8");
            response.setCharacterEncoding("utf-8");
            return "下载成功";
        } catch (IOException e) {
            e.printStackTrace();
        }
        return "下载失败";
    }

FileUtil工具类:

public class FileUtil {
    public static void down(HttpServletResponse res, String pathAddress) throws UnsupportedEncodingException {
        File file=new File(pathAddress);
        String fileName = file.getName();

        res.setHeader("content-type", "application/octet-stream");
        res.setContentType("application/octet-stream");
        res.setHeader("Content-Disposition", "attachment;filename=" + new String(fileName.getBytes("utf-8"),"iso-8859-1"));
        byte[] buff = new byte[1024];
        FileInputStream bis = null;
        OutputStream os = null;
        try {
            os = res.getOutputStream();
            bis = new FileInputStream(file);
            int readTmp = 0;
            while ((readTmp = bis.read(buff)) != -1) {
                os.write(buff, 0, readTmp);
            }
        } catch (IOException e) {
            e.printStackTrace();
        } finally {
            if (bis != null) try {
                bis.close();
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
        System.out.println("文件下载成功!");
    }
}

  • 4
    点赞
  • 37
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值