什么鬼_呀你
2018-07-31 18:52:17浏览 2731
<!----html页面-->
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8" />
<meta http-equiv="X-UA-Compatible" content="IE=edge">
<title>上传文件</title>
<meta name="viewport" content="width=device-width, initial-scale=1">
</head>
<body>
文件:<input type="file" multiple id="fileList">
<br>
<table border="2">
<caption>文件详情</caption>
<thead>
<tr>
<th>文件名</th>
<th>类型</th>
<th>大小(/kb)</th>
<th>上传</th>
<th>下载</th>
</tr>
</thead>
<tbody id="content">
</tbody>
</table>
<div id="content">
</div>
<script src="ajax.js"></script>
<script>
let files=document.getElementById('fileList'),
content=document.getElementById('content'),
arr=['name','type','size'],
index=0;
fileArr=[];//存储文件
files.onchange=function(event){
let files=this.files,
len=files.length;
if(len){
for(let f=0;f<len;f++){
let file=files[f],
tr = content.insertRow(index++);
for (let x = 0; x < 5; x++) {
let td = tr.insertCell(x);
if(x>=arr.length){
if(x==3)td.innerHTML='<a href="javascript:;" id="'+index+'" ="up()">上传</a>';
if(x==4)td.innerHTML='<a href="javascript:;" ="down()">下载</a>'
}else{
td.innerHTML = file[arr[x]];
}
}
fileArr.push(file);
}
}
}
function up(){
let index=(event.target.id)-1,
data=fileArr[index],
url='http://localhost:7000/upload';
ajax({
url:url,
data:data
})
}
</script>
</body>
</html>
ajax页面
function ajax(obj) {
let {url,data}=obj;
if (XMLHttpRequest)
xhr = new XMLHttpRequest();
else if (ActiveXObject){
xhr = new ActiveXObject('Micorsoft.HTTP');
}
xhr.open('post', url, true);
xhr.setRequestHeader('Content-Type', 'application/x-www-form-urlencoded');
//xhr.send(data);
let reader = new FileReader(), type = data.type;
console.log(type)
if (data.type.indexOf('text') > -1)//文本文件
reader.readAsText(data);
else if (data.type.indexOf('image') > -1)//图片文件
reader.readAsDataURL(data);
reader. = function () {
xhr.send(`name=${data.name}&type=${data.type}&file=${reader.result}`);
}
xhr.onreadystatechange = function () {
if (xhr.readyState == 4) {
if (xhr.status == 200 || xhr.status == 304) {
alert(xhr.responseText)
}
}
}
}
<!--后端服务器nodejs-->
const express = require('express'),
bodyparser = require('body-parser'),
fs = require('fs'),
app = express();
app.use(bodyparser.json({ limit: '50mb' }));
app.use(bodyparser.urlencoded({ limit: '50mb', extended: true }));
//判断目录是否存在
let url = __dirname + '/temp_up/';
fs.exists(url,(exists)=>{
if(!exists)fs.mkdir(url);
})
app.post('/upload', (req, res) => {
res.setHeader("Access-Control-Allow-Origin", "*");
let {name,type,file}=req.body;
if (type.includes('text')){
fs.writeFile(url+name,file,'utf-8',(err)=>{
if(err)console.log('写入失败!')
})
}else if(type.includes('image')){
file = file.substring(23);
fs.writeFile(url+name, file, 'base64', (err) => {
//没有报错,图片不正显示,why???
if (err) console.log(err)
})
}
res.send('success!')
})
app.listen(7000, () => {
console.log('server running on 7000....');
})
//重点在服务端代码中,图片文件读取后写入文件显示不出来,怎么办????