上传和下载

本文详细介绍了通过HTML表单和AJAX实现文件上传的方法,包括同域与跨域上传的处理技巧,以及使用FormData和FileReader进行上传的示例。同时,探讨了多种文件下载策略,如利用文件流、a标签、window.open和form表单实现文件下载。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

上传

一:form表单方式

1.表单提交地址和当前页面在同一个域(http://localhost:3000)

html:

<form action="http://localhost:3000" method="post" enctype="multiple/form-data" target="iframe1">
	<input type="file" name="file" multiple id="upfile1" value="">
	<input type="hidden" name="username" value="admin">
	<input type="hidden" name="password" value="123456">
	<input type="submit" name="submit" value="提交上传">
</form>
<iframe id="id_iframe" name="iframe1" style="display: none"></iframe>

js:

var iframe = document.querySelector('#id_iframe')
iframe.onload = function(){
    var iw = this.contentWindow;
    var code = iw.document.querySelector('#code');
    var msg = iw.document.querySelector('#msg');
    //上传完成后返回的数据
    console.log(code,msg)
			
}

后端nodejs:

const http = require('http');
let server = http.createServer(function(req,res){
	if(req.url == '/favicon.ico'){
		return
	}
	
res.writeHead(200,{'content-Type':'text/html;charset=UTF8'})
	res.end(`
		<div id='code'>200</div>
		<div id='msg'>上传成功</div>
		`)

}).listen(3000)

2.表单提交地址(http://localhost:3001)和当前页面(http://localhost:3000)存在跨域

html:

<form action="http://localhost:3001" method="post" enctype="multiple/form-data" target="iframe1">
	<input type="file" name="file" multiple id="upfile1" value="">
	<input type="hidden" name="username" value="admin">
	<input type="hidden" name="password" value="123456">
	<input type="submit" name="submit" value="提交上传">
</form>
<iframe id="id_iframe" name="iframe1" style="display: none"></iframe>

js:

var iframe = document.querySelector('#id_iframe')
iframe.onload = function(){
    //使用postMessage通信,解决跨域
    iw.postMessage(' 上传成功了吗','http://localhost:3001')//表单提交完毕,向iframe发送数据
    window.onmessage = function(e){
        //接收返回的数据
        console.log('上传完成后返回的数据'+e.data)
    }
}

后端nodejs:

const http = require('http');
let server = http.createServer(function(req,res){
	if(req.url == '/favicon.ico'){
		return
	}
	
res.writeHead(200,{'content-Type':'text/html;charset=UTF8'})
	res.end(`
        <script>
        var data = {
            "code":200,
            "msg":"上传成功"
        }
        window.onmessage = function(e){
            console.log('接收父页面传递的数据'+e.data)
            //向父页面响应数
            e.source.postMessage(JSON.stringify(data),'http://localhost:3000')
        }
        </script>
		`)
}).listen(3000)

 二.ajax上传

1.使用FormData

html:

<div>
	<input type="file" name="file" multiple id="upfile2" value="">
	<button type="button" id="btn2">点击上传</button>
</div>

js:

var btn2 = document.querySelector('#btn2');
 btn2.addEventListener('click',function(){
	var fileObj =document.querySelector('#upfile2').files;//获取文件对象
	var xhr = new XMLHttpRequest();
	xhr.open('POST','http://localhost:3000');
	xhr.onreadystatechange = function(){
		if(xhr.readyState === 4){
			if(xhr.status>=200&&xhr.status<300||xhr.status===304){
				console.log(xhr.response)
			}
		}
	}
	var data = new FormData();
	data.append('username','admin');
	data.append('password','123456');
	data.append('file',fileObj)
	xhr.send(data);	
})

 2.使用fileReader

html:

<div>
	<input type="file" name="file" multiple id="upfile2" value="">
	<button type="button" id="btn2">点击上传</button>
</div>

js:

var btn2 = document.querySelector('#btn2');
btn2.addEventListener('click',function(){
	var fileObj =document.querySelector('#upfile2').files[0];//获取文件对象
	var fr = new FileReader();
	fr.readAsDataURL(fileObj)
	fr.onload = function(){
		var res = this.result;
		var xhr = new XMLHttpRequest();
		xhr.open('POST','http://localhost:3000');
		xhr.onreadystatechange = function(){
			if(xhr.readyState === 4){
				if(xhr.status>=200&&xhr.status<300||xhr.status===304){
					console.log(xhr.response)
				}
			}
		}
		xhr.send(res);
	}
})

二.下载

<!DOCTYPE html>
<html lang="en">
<head>
	<meta charset="UTF-8">
	<title>下载</title>
</head>
<body>
	<button type="button" id="one">点击下载1</button>
	<button type="button" id="two">点击下载2</button>
	<button type="button" id="three">点击下载3</button>
	<button type="button" id="four">点击下载4</button>
	<script>
		var btn1 = document.querySelector('#one');
		var btn2 = document.querySelector('#two');
		var btn3 = document.querySelector('#three');
		var btn4 = document.querySelector('#four');
		/*1.文件流*/
		btn1.addEventListener('click',function(){
			var content = 'haha';//类型:ArrayBuffer,ArrayBufferView,Blob,DOMString
			var file = new File([content],'text.txt',{type:'text/plain'});//File(bits,name[,options]),options.type:文件内容的MIME类型,options.lastModified:文件最后修改时间
			var url = URL.createObjectURL(file)
			var a = document.createElement('a')
			a.href= url;
			a.download =file.name
			a.style.display = 'none'
			document.body.appendChild(a)
			a.click();
			URL.revokeObjectURL(url)
			a.remove()
		})
		/*2.文件地址+a标签*/
		btn2.addEventListener('click',function(){
			var a = document.createElement('a')
			a.href= 'D:/workspase/exercise/views/onload.html';//文件地址或者下载接口地址
			a.download = 'onload.html'
			a.style.display = 'none'
			document.body.appendChild(a)
			a.click();
			a.remove()
		})
		/*3.文件下载地址+window.open*/
		btn3.addEventListener('click',function(){
			var url = 'http://www.xxx.com/book.doc';//下载接口地址
			window.open(url,'_blank')
		})
		/*4.文件下载地址+from表单*/
		btn4.addEventListener('click',function(){
			var url = 'http://www.xxx.com/book.doc';//下载接口地址
			var elForm = document.createElement('form');
			elForm.setAttribute('method','get')
			elForm.setAttribute('action',url)
			document.body.appendChild(elForm);
			elForm.submit();//提交表单
			elForm.remove();//删除表单
		})
	</script>
</body>
</html>

 

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值