记录基于mongoDB的文件上传下载

一、MongoDB环境部署

选择版本下载:https://www.mongodb.org/dl/linux

上传到服务器解压到某路径mongodb目录

进入mongodb目录下,新建data目录和logs目录

进入mongodb\bin目录,编辑mongodb.conf文件

dbpath= /某路径/mongodb/data/db
logpath= /某路径/mongodb/logs/mongodb.log
port= 27017
fork= true
auth= true
bind_ip= 127.0.0.1   #服务器IP

在bin目录下

启动

./mongod --journal -f ./mongodb.conf

停止

./mongod --journal --shutdown -f ./mongodb.conf

二、后端代码

1.SpringBoot集成MongoDB

pom.xml中添加依赖

<!-- MongoDb -->
<dependency>
    <groupId>org.springframework.boot</groupId>
    <artifactId>spring-boot-starter-data-mongodb</artifactId>
</dependency>

Spring配置

spring:
  data:
    mongodb:
      uri: mongodb://username:pwd@127.0.0.1:27017/database

2.文件上传

controller层

@ApiOperation(value = "文件上传",notes = "文件上传")
@RequestMapping(value = "upload",method = RequestMethod.POST)
@ResponseBody
public OperationResult uploadFile(@RequestParam("file") MultipartFile[] files){
    OperationResult result = fileService.uploadFile(files);
    return result;
}

service层

@Override
public OperationResult uploadFile(MultipartFile[] files) {
	OperationResult result = OperationResult.OK();
    List fileInfos = new ArrayList<>();
    if(ObjectUtils.isEmpty(files)||files.length<1){
        return OperationResult.ERROR("无文件上传");
    }
    try{
        for(MultipartFile file:files){
            String fileName = file.getOriginalFilename();
            InputStream ins = file.getInputStream();
            String contentType = file.getContentType();
            ObjectId objectId = gridFsTemplate.store(ins, fileName, contentType);
            fileInfos.add(fileName+"@ITAM@"+objectId.toString());
        }
        result.addObjectData("fileInfos",fileInfos);
    }catch (Exception e){
        return OperationResult.ERROR("上传文件异常");
    }
    return result;
}

3.文件下载

controller层

@ApiOperation(value = "下载文件",notes="下载文件")
@RequestMapping(value = "download",method = RequestMethod.POST)
@ResponseBody
public OperationResult download(@RequestParam("fileId") String fileId,HttpServletRequest request, HttpServletResponse response) throws IOException {
    // 查询单个文件
    GridFSFile gridFSFile = fileService.queryFileFormMongo(fileId);
    if (gridFSFile == null) {
        return OperationResult.ERROR("下载文件失败");
    }
    String fileName = gridFSFile.getFilename().replace(",", "");
    String contentType = gridFSFile.getMetadata().get("_contentType").toString();
    response.setContentType(contentType);
    response.setHeader("Content-Disposition", "attachment;filename=\"" + URLEncoder.encode(fileName, "UTF-8") + "\"");
    //创建一个文件桶
    GridFSBucket gridFsBucket = GridFSBuckets.create(mongoTemplate.getDb());
    InputStream inputStream = null;
    OutputStream outputStream = null;
    try {
        if (gridFSFile!=null) {
            // 打开下载流对象
            GridFSDownloadStream fileStream = gridFsBucket.openDownloadStream(gridFSFile.getObjectId());
            // 创建girdFsResource,传入下载流对象,获取流对象
            GridFsResource gridFsResource = new GridFsResource(gridFSFile, fileStream);
            // 写入输出流
            inputStream = gridFsResource.getInputStream();
            outputStream = response.getOutputStream();
            IOUtils.copy(inputStream,outputStream);
            outputStream.flush();
        }
    } catch (IOException e) {
        return OperationResult.ERROR("下载文件异常");
    } finally {
        outputStream.close();
        inputStream.close();
    }
    return null;
}

service层

@Override
public GridFSFile queryFileFormMongo(String fileId) {
    GridFSFile gridFSFile;
    try{
        // 查询单个文件
        Query query = Query.query(Criteria.where("_id").is(fileId));
        gridFSFile = gridFsTemplate.findOne(query);
    }catch(Exception e){
        return null;
    }
    return gridFSFile;
}

三、前端代码

1.文件上传

<el-upload
	class="upload-demo uploadAttachment"
	ref="upload"
	drag
	action=""
	multiple
	accept=".doc,.docx,.xls,.xlsx,.pdf,.jpg,.png"
	:headers="uploadHeaders"
	:file-list="fileList"
	:on-change="onChange"
	:auto-upload="false"
	:http-request="httpRequest">
	<div class="picture">
	</div>
	<div class="el-upload__text">点击或将文件拖拽到这里上传</div>
	<div class="el-upload__tip" slot="tip">
		支持扩展名:.doc, .docx, .pdf, .xls, .xlsx, .jpg, .png 
	</div>
</el-upload>
<el-button type="primary" @click="submitForm('ruleForm')">提交</el-button
export default {
	data(){
		fileList:[],
		uploadHeaders: {
        headers: {
          'Content-Type':'multipart/form-data'
        }
      }
	},
	methods:{
		submitForm(){
			var formObj = new FormData()
      		this.$refs.upload.submit()
      		this.fileList.forEach(function (file){
        		formObj.append('files',file)
      		})
      		FileApi.uploadFile(formObj).then(response => {
        		if (response.status === 'OK') {
          			this.$router.go(-1);
          			this.$message.success("保存成功");
        		} else if(response.status === 'ERROR') {
          			alert(response.msg);
        		}else{
          			alert("新增失败")
        		}
      		})
		},
		// 自定义的上传函数
    	httpRequest(param) {
      		// 一般情况下是在这里创建FormData对象,但我们需要上传多个文件,为避免发送多次请求,因此在这里只进行文件的获取,param可以拿到文件上传的所有信息
      		this.fileList.push(param.file)
    	},
		onChange(file,fileList){
		    let suffix = this.getFileSuffix(file.name)
		    let suffixArray = ['doc','docx','xls','xlsx','pdf','jpg','png'] //限制的文件类型,根据情况自己定义
		    if (suffixArray.indexOf(suffix) === -1) {
		    	this.$message.error('上传文件格式错误')
		        fileList.pop()
		        return
		    }
		    let fileSize = file.size/1024/1024
		    if(fileSize>20){
		        this.$message.error('上传文件不能超过20M')
		    	fileList.pop()
		        return
		    }
		    },
		    getFileSuffix(name){
		    	let startIndex = name.lastIndexOf('.')
		      	if (startIndex !== -1) {
		        	return name.slice(startIndex + 1).toLowerCase()
		      	} else {
		        	return ''
		      	}
		    },
	}
}

2.文件下载

<span class="table-operator" v-for="(fileInfo, index) in activity.fileInfos" @click="fileDownload(fileInfo)">
	{{ fileInfo!=null?fileInfo.fileName:'' }}
</span>
fileDownload(fileInfo){
      let params = {
        fileId:fileInfo.fileId
      }
      const loading = this.$loading({
        lock: true,
        text: 'Loading',
        spinner: 'el-icon-loading',
        background: 'rgba(0, 0, 0, 0.7)'
      });

      axios({
        url: 'file/download',
        method: 'post',
        data:qs.stringify(params),
        responseType: 'blob'
      }).then(res => {
        let blob = new Blob([res]);
        if(window.navigator.msSaveBlob){
          //IE11兼容处理
          window.navigator.msSaveBlob(blob, fileInfo.fileName);
        }else{
          let fileUrl = window.URL.createObjectURL(blob); // 创建导出的链接
          let link = document.createElement('a');
          link.href = fileUrl;
          link.download = fileInfo.fileName;
          document.body.appendChild(link)
          link.click() // 点击导出
        }
      }).finally(_ => {
        //关闭-进度条.
        loading.close()
      })
    }
  • 0
    点赞
  • 4
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值