前端、后端node.js文件上传下载

前端实现文件上传

    <body>
		<!-- 没有设置多选,只能选择一个文件 -->
		<input type="file" id="file"/>
	</body>
	<script>
		// 获取文件选择控件
		var file = document.getElementById('file');
		// 为文件选择控件添加onchanges事件
		// 在用户文件选择时触发
		file.onchange = function(){
			// 创建空的formData
			var formData = new FormData();
			// 将用户选择的文件追加到formData表单对象中
			formData.append('attrName',this.files[0]);
			//	this.files[0] this指向file,用户选择的文件
			// 创建ajax对象
			var xhr = new XMLHttpRequest();
			// 对ajax对象进行配置
			// 只有post方法能实现文件上传
			xhr.open('post','http://localhost:3000/upload')
			// 把文件发送到服务端 发送ajax请求
			xhr.send(formData);
			// 监听服务器端响应给客户端的数据
			xhr.onload = function(){
				// 如果服务器端返回的http状态码为200 请求成功
				if(xhr.status == 200){
					// 将服务器端返回的数据显示在控制台中
					console.log(xhr.responseText);
				}else{
					console.log("上传失败,出错了")
				}
			}
		}
		
	</script>

demo

<!DOCTYPE html>
<html lang="en">
  <head>
    <meta charset="UTF-8" />
    <meta http-equiv="X-UA-Compatible" content="IE=edge" />
    <meta name="viewport" content="width=device-width, initial-scale=1.0" />
    <title>Document</title>
  </head>
  <body>
    <input type="file" id="file" />
  </body>
  <script>
    // 获取文件选择控件
    var file = document.getElementById('file')
    // 为文件选择控件添加onchanges事件
    // 在用户文件选择时触发
    file.onchange = function () {
      // 创建空的formData
      var formData = new FormData()
      // 将用户选择的文件追加到formData表单对象中
      formData.append('file_upload', this.files[0])
      //	this.files[0] this指向file,用户选择的文件
      // 创建ajax对象
      var xhr = new XMLHttpRequest()
      // 对ajax对象进行配置
      // 只有post方法能实现文件上传
      xhr.open('post', 'http://192.168.1.222:90/x86/system_file_settings/')
      xhr.setRequestHeader(
        'Authorization',
        'token eyJ0eXAiOiJKV1QiLCJhbGciOiJIUzI1NiJ9.eyJpZCI6MiwibmFtZSI6InVzZXIifQ.gRG1xnin3_zhRCWgGXEmo5JtB7mctN50Jvht37CeNqI'
      )
      // 把文件发送到服务端 发送ajax请求
      xhr.send(formData)
      // 监听服务器端响应给客户端的数据
      xhr.onload = function () {
        // 如果服务器端返回的http状态码为200 请求成功
        if (xhr.status == 200) {
          // 将服务器端返回的数据显示在控制台中
          console.log(xhr.responseText)
        } else {
          console.log('上传失败,出错了')
        }
      }
    }
  </script>
</html>

上传文件进度条显示

<body>
		<!-- 没有设置多选,只能选择一个文件 -->
		<input type="file" id="file"/>
		<div class="progress">
			<div class="progress-bar" style="width:70%" id="bar">70%</div>
			
		</div>
	</body>
	<script>
		// 获取文件选择控件
		var file = document.getElementById('file');
		var bar = document.getElementById('bar');

		// 为文件选择控件添加onchanges事件
		// 在用户文件选择时触发
		file.onchange = function(){
			// 创建空的formData
			var formData = new FormData();
			// 将用户选择的文件追加到formData表单对象中
			formData.append('attrName',this.files[0]);
			//	this.files[0] this指向file,用户选择的文件
			// 创建ajax对象
			var xhr = new XMLHttpRequest();
			// 对ajax对象进行配置
			// 只有post方法能实现文件上传
			xhr.open('post','http://localhost:4040/upload');
			// onprogress在文件上传的过程中持续触发
			xhr.upload.onprogress = function(ev){
				// ev.loaded 文件已经上传了多少
				// ev.total  上传文件的问大小
				var result = (ev.loaded / ev.total) * 100 + '%';
				// 设置进度条的宽度
				bar.style.width = result;
				// 将百分比显示在进度条中
				bar.innerHTML = result;
				console.log(ev);
			}
			
			// 把文件发送到服务端 发送ajax请求
			xhr.send(formData);
			// 监听服务器端响应给客户端的数据
			xhr.onload = function(){
				// 如果服务器端返回的http状态码为200 请求成功
				if(xhr.status == 200){
					// 将服务器端返回的数据显示在控制台中
					console.log(xhr.responseText);
					console.log('成功')
				}else{
					console.log("上传失败,出错了")
				}
			}
		}
		
	</script>

elementui 文件上传

 <el-form-item :label='itemLabel'>
            <template slot='label'>
              <i class='el-icon-help'></i>
              {{itemLabel}}
            </template>
            <el-upload
              ref='upload'
              class='upload-demo'
              :accept='accept'
              :action='action'
              :on-preview='handlePreview'
              :on-remove='handleRemove'
              :before-remove='beforeRemove'
              :on-success='successPreview'
              :headers='token'   //绑定token
              :show-file-list='true'
              :limit='1'
              :on-exceed='handleExceed'
              :auto-upload='false'
              :http-request='myUploadFile'
              name='file_upload'
              :file-list='fileList'>
              <el-button slot='trigger' size='small' type='success'><i class='el-icon-plus'></i>&nbsp;选择文件</el-button>
              <el-button style='margin-left: 10px;' size='small' type='primary' @click='submitUpload'><i class='el-icon-upload'></i>&nbsp;上传文件
              </el-button>
              <slot name='download'></slot>
              <el-button size='small' type='warning' v-if='ifConfig' @click='download'><i class='el-icon-download'></i>&nbsp;导出配置</el-button>
              <slot name='center'></slot>
              <!--      <div slot='tip' class='el-upload__tip'>只能上传压缩文件</div>-->
            </el-upload>
          </el-form-item>



 async myUploadFile(data) {
       let file = data.file
       if (this.type === 'image_btn') {
         let formData = new FormData()
         formData.append('img_upload', file)
         uploadImageAPI(formData).then(res => {

           if (res.data.message !== '上传成功') {
             // alert("上传失败")
             this.$confirm('', res.data.errorMes, {
               confirmButtonText: '确定',
               type: 'error',
               showCancelButton: false,
               closeOnClickModal: false,
               center: true
             })
           } else {
             this.fileList = []
             this.$confirm('', res.data.message, {
               confirmButtonText: '确定',
               type: 'success',
               showCancelButton: false,
               closeOnClickModal: false,
               center: true
             })

           }

         }).catch(() => {
           loading.close()
           // this.submitLoading = false;
         })
         // this.action = 'http://192.168.1.222:90/x86/img_upload/'
       }

前端实现下载文件

  1. 调用接口设置responseType类型为blob
export const uploadAudioVideofiles = (data) => {
  return request.get(`/x86/get_audio_and_video_files/`,{params:data,responseType:'blob'})
}

2.获取后端返回的文件名,拿到请求头(content-disposition)的值

 const fileName = decodeURI(res.headers['content-disposition'].split(';')[1].split('=')[1])
download() {
	      getSystemConfig().then(res => { //后端返回的res
	        const link = document.createElement('a')
	        let blob = new Blob([res.data], { type: 'application/zip' }) //类型
	        link.style.display = 'none'
	        link.href = URL.createObjectURL(blob)
	        link.setAttribute('download', 'data_config')  //data_config为下载的文件名    
	        document.body.appendChild(link)
	        link.click()
	        document.body.removeChild(link)
	        this.$message.success('导出配置')
	
	      })

  },
// 将blob转换为url
 getURL(file) {
  let url = null;
  if (window.createObjectURL !== undefined) {
    // basic
    url = window.createObjectURL(file);
  } else if (window.webkitURL !== undefined) {
    // webkit or chrome
    try {
      url = window.webkitURL.createObjectURL(file);
    } catch (error) { }
  } else if (window.URL !== undefined) {
    // mozilla(firefox)
    try {
      url = window.URL.createObjectURL(file);
    } catch (error) { }
  }
  return url;
}

直接用的方法

  download(res) {
        const link = document.createElement('a')
        const fileName = decodeURI(res.headers['content-disposition'].split(';')[1].split('=')[1])
        let name = fileName.replace(/"/g, '');
        let new_name = name.split('.')
        let end_type = new_name[new_name.length-1]
      //   if(end_type.startsWith("mp3")){
      //     var blob = new Blob([data], { type: 'application/mp3' })
      //   }else if (end_type.startsWith("mp4")){
      //     var blob = new Blob([data], { type: 'application/mp4' })
      //   }
        var blob = new Blob([res.data], { type: `application/${end_type}` })
        link.style.display = 'none'
        link.href = URL.createObjectURL(blob)
        link.setAttribute('download', name)
        document.body.appendChild(link)
        link.click()
        document.body.removeChild(link)
    },
    //等待所有文件下载完成
     const promises = this.selections.map(item => {
         return new Promise((resolve, reject) => {
           uploadAudioVideofiles({
             "file_path": item.targetPath
           }).then((res) => {
             this.download(res)
             resolve(); // 成功时解析 Promise
           }).catch(error => {
             reject(error); // 失败时拒绝 Promise
           });
         });
       });
       try {
         await Promise.all(promises);
         this.$message.success("下载完成");
       } catch (error) {
         console.error(error);
         this.$message.error("下载失败");
       }

node.js后端实现文件上传

方法一

const experss = require('express');
const path = require('path');
const fs = require('fs');
const formidable = require('formidable');
var svgCaptcha = require('svg-captcha');
const app = experss();
app.listen(3000, () => {
    console.log(`web服务器工作在3000端口`);
});
//文件上传界面:
app.get('/uploads', (req, res) => {
    res.sendFile(path.join(__dirname, 'users.html'));
});
//处理含有文件上传的表单
app.post('/doupload', (req, res) => {
    let filePath = path.join(__dirname, 'uploads');
    //判断目录或文件是否存在:
    if (!fs.existsSync(filePath)) { //目录不存在时
        fs.mkdirSync(filePath); //创建目录
    }
    //uploadDir:设置文件上传成功后的存放位置
    //初始化
    const form = formidable({ multiples: true, uploadDir: filePath });
    // console.log(form, 333);

    form.parse(req, (err, fields, files) => {
        // console.log(err, fields, files, 111);
        if (err) { //表单处理失败
            res.send('表单处理失败');
        } else { //表单处理成功 
            //获取用户选择的要上传文件的文件名:
            let ufilename = files.pic.originalFilename;
            //获取用户选择的要上传文件的文件扩展名:
            let extNames = path.extname(ufilename);
            // console.log(extNames, 666);
            //使用自已生成新随机文件名:  完整文件名=文件名.扩展名
            //  form表单要设置成enctype="multipart/form-data",pic是文件上传input type="file"的name
            let fullname = `${files.pic.newFilename}${extNames}`
            console.log(fullname);
            //将上传成功后生成的临时文件名改为正式文件名
            fs.renameSync(files.pic.filepath, `${filePath}/${fullname}`);
            res.send('OK')
        }
    });


});

方法二


```javascript
app.post('/upload',(req,res)=>{
	//创建formidable表单解析对象
	const form = new formidadle.IncomingForm();
	//设置客户端上传文件的存储路径
	form.uploadDir = path.join(__dirname,'public','uploads');
	//保留上传文件的后缀名字
	form.keepExtensions = true;
	//解析客户端传递过来的FormData对象
	form.parse(req,(err,fields,files)=>{
		res.send('ok');
	}) 
})

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

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

CongJiYong

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值