springboot上传zip包并解压至服务器nginx目录
此案例场景为:
从前端上传.zip 包,并进行解压至 docker容器内(服务部署使用了docker),然后容器内部解压目录与 宿主机(linux)nginx 目录的html 进行挂载,这样,就可以通过nginx 来访问上传解压出来的文件了。
那么具体看怎么实现,下面会贴上相关代码:
1.首先需要引入zip相关jar包
net.lingala.zip4j zip4j 1.3.1
2.然后我直接贴controller 代码了
package com.fnm.feynman.smartvillage.admin.controller; import com.diboot.core.vo.jsonresult; import com.fnm.feynman.smartvillage.business.entity.regionvillage; import com.fnm.feynman.smartvillage.business.service.regionvillageservice; import io.swagger.annotations.apioperation; import lombok.extern.slf4j.slf4j; import net.lingala.zip4j.core.zipfile; import net.lingala.zip4j.exception.zipexception; import org.apache.commons.io.fileutils; import org.springframework.beans.factory.annotation.autowired; import org.springframework.web.bind.annotation.pathvariable; import org.springframework.web.bind.annotation.postmapping; import org.springframework.web.bind.annotation.requestmapping; import org.springframework.web.bind.annotation.restcontroller; import org.springframework.web.multipart.multipartfile; import java.io.file; import java.io.ioexception; /** * @author yanjun.liu * @date 2020/12/24--16:41 */ @slf4j @restcontroller @requestmapping("/admin/open") public class uploadvrcontroller { @autowired private regionvillageservice regionvillageservice; /** * https://www.cnblogs.com/0616--ataozhijia/p/5022028.html * @param id 村庄id * @param file 上传的vr * @throws ioexception * 上传到docker容器内 /opt下,并解压,然后宿主机和容器内路径进行挂载,外部挂载地址为nginx服务器html 目录 */ @apioperation("上传vr") @postmapping("/uploadvr/{id}") public jsonresult uploadvr(@pathvariable("id") long id, multipartfile file) throws ioexception, zipexception { regionvillage entity = regionvillageservice.getentity(id); file file1 = new file("/opt/" + entity.getvalue()+".zip"); //上传文件到服务器/opt/目录下 //file file1 = new file("e:/zip/" + entity.getvalue()+".zip"); fileutils.writebytearraytofile(file1,file.getbytes()); zipfile zipfile = new zipfile(file1); //给的vr是gbk,如果这里,你上传的zip包为utf-8,那么这里改为utf-8 zipfile.setfilenamecharset("gbk"); string path="/opt/"+entity.getvalue(); //解压到指定目录 zipfile.extractall(path); string substring = file.getoriginalfilename().substring(0, file.getoriginalfilename().indexof(".")); //将解压到nginx 目录的路径地址拼接为可访问的url ,进行修改实体对象 entity.setvrurl("https://**ed.*****.com/vr/"+entity.getvalue()+"/"+substring+"/output/index.html"); regionvillageservice.updateentity(entity); return jsonresult.ok(); } }
3.说明上面上传的/opt/目录为docker容器里面的目录
那么我需要将容器里面的目录和宿主机nginx目录进行挂载后,才能通过http请求访问
具体如何挂载呢?
关键:
-v /usr/local/nginx/html/vr:/opt
前面为宿主机nginx的静态文件目录,:后面为容器内部目录,这个配置智慧解压缩后的文件就会同步到 nginx html目录下,就可以访问了
docker run -d -p 4011:4011 --net mynet --name feynman-smart-village-admin -v /usr/local/nginx/html/vr:/opt feynman-smart-village-admin:latest
至此 上传zip 解压 至服务器就完成了~
总结
以上为个人经验,希望能给大家一个参考,也希望大家多多支持代码网。
海报
141