今年国庆假期终于可以憋在家里了不用出门了,不用出去看后脑了,真的是一种享受。这么好的光阴怎么浪费,睡觉、吃饭、打豆豆这怎么可能(耍多了也烦),完全不符合我们程序员的作风,赶紧起来把文章写完。
这篇文章比较基础,在国庆期间的业余时间写的,这几天又完善了下,力求把更多的前端所涉及到的关于文件上传的各种场景和应用都涵盖了,若有疏漏和问题还请留言斧正和补充。
以下是本文所涉及到的知识点,break or continue ?
原理很简单,就是根据 http 协议的规范和定义,完成请求消息体的封装和消息体的解析,然后将二进制内容保存到文件。
我们都知道如果要上传一个文件,需要把 form 标签的enctype设置为multipart/form-data,同时method必须为post方法。
那么multipart/form-data表示什么呢?
multipart互联网上的混合资源,就是资源由多种元素组成,form-data表示可以使用HTML Forms 和 POST 方法上传文件,具体的定义可以参考RFC 7578。
multipart/form-data 结构
看下 http 请求的消息体
Content-Type: multipart/form-data; boundary=----WebKitFormBoundaryDCntfiXcSkPhS4PN 表示本次请求要上传文件,其中boundary表示分隔符,如果要上传多个表单项,就要使用boundary分割,每个表单项由———XXX开始,以———XXX结尾。
每一个表单项又由Content-Type和Content-Disposition组成。
Content-Disposition: form-data 为固定值,表示一个表单元素,name 表示表单元素的 名称,回车换行后面就是name的值,如果是上传文件就是文件的二进制内容。
Content-Type:表示当前的内容的 MIME 类型,是图片还是文本还是二进制数据。
解析
客户端发送请求到服务器后,服务器会收到请求的消息体,然后对消息体进行解析,解析出哪是普通表单哪些是附件。
可能大家马上能想到通过正则或者字符串处理分割出内容,不过这样是行不通的,二进制buffer转化为string,对字符串进行截取后,其索引和字符串是不一致的,所以结果就不会正确,除非上传的就是字符串。
不过一般情况下不需要自行解析,目前已经有很成熟的三方库可以使用。
至于如何解析,这个也会占用很大篇幅,后面的文章在详细说。
使用 form 表单上传文件
在 ie时代,如果实现一个无刷新的文件上传那可是费老劲了,大部分都是用 iframe 来实现局部刷新或者使用 flash 插件来搞定,在那个时代 ie 就是最好用的浏览器(别无选择)。
DEMO
这种方式上传文件,不需要 js ,而且没有兼容问题,所有浏览器都支持,就是体验很差,导致页面刷新,页面其他数据丢失。
HTML
<form method="post" action="http://localhost:8100" enctype="multipart/form-data">
选择文件:
<input type="file" name="f1"/> input 必须设置 name 属性,否则数据无法发送<br/>
<br/>
标题:<input type="text" name="title"/><br/><br/><br/>
<button type="submit" id="btn-0">上 传</button>
</form>
复制代码
服务端文件的保存基于现有的库koa-body结合 koa2实现服务端文件的保存和数据的返回。
在项目开发中,文件上传本身和业务无关,代码基本上都可通用。
在这里我们使用koa-body库来实现解析和文件的保存。
koa-body 会自动保存文件到系统临时目录下,也可以指定保存的文件路径。
然后在后续中间件内得到已保存的文件的信息,再做二次处理。
NODE
/**
* 服务入口
*/
var http = require('http');
var koaStatic = require('koa-static');
var path = require('path');
var koaBody = require('koa-body');//文件保存库
var fs = require('fs');
var Koa = require('koa2');
var app = new Koa();
var port = process.env.PORT || '8100';
var uploadHost= `http://localhost:${port}/uploads/`;
app.use(koaBody({
formidable: {
//设置文件的默认保存目录,不设置则保存在系统临时目录下 os
uploadDir: path.resolve(__dirname, '../static/uploads')
},
multipart: true // 开启文件上传,默认是关闭
}));
//开启静态文件访问
app.use(koaStatic(
path.resolve(__dirname, '../static')
));
//文件二次处理,修改名称
app.use((ctx) => {
var file = ctx.request.files.f1;//得道文件对象
var path = file.path;
var fname = file.name;//原文件名称
var nextPath = path+fname;
if(file.size>0 && path){
//得到扩展名
var extArr = fname.split('.');
var ext = extArr[extArr.length-1];
var nextPath = path+'.'+ext;
//重命名文件
fs.renameSync(path, nextPath);
}
//以 json 形式输出上传文件地址
ctx.body = `{
"fileUrl":"${uploadHost}${nextPath.slice(nextPath.lastIndexOf('/')+1)}"
}`;
});
/**
* http server
*/
var server = http.createServer(app.callback());
server.listen(port);
console.log('demo1 server start ...... ');
复制代码
CODE
https://github.com/Bigerfe/fe-learn-code/
013年,在Google工作的尤雨溪,开发出了一款轻量Javascript框架,最初命名为Seed,同年12月,更名为Vue,一经推出发展迅速,如今已成为最时髦和炙手可热前端框架,在Github上获得了超过十万的Star,国内许多知名公司都使用Vue作为前端开发工具,例如饿了么、美团等,很多公司的招聘要求都会把会使用vue作为加分项。
Vue的作者 - 尤雨溪
001-Vue的定位是什么?
Vue是一个JavaScript框架,类似的框架有React,Angular等等,所谓框架就是一个比较大型的库,使用它能让基于网页的前端应用程序开发起来更加方便。相对于完全采用原生JavaScript代码来编写前端代码而言,使用框架的代码量更少,开发效率也更高。
需要注意的是,Vue并非UI框架,它的定位与Bootstrap、Frozen UI这一类专注于页面呈现的框架不是一回事,或者说,UI框架关注点在HTML,而Vue这一类框架关注点是JavaScript。Vue可以跟很多UI框架搭配使用,比如说Bootstrap(vueBootstrap),和一些专门与Vue配合的例如饿了吗团队开发的element-ui等等。
002-实现第一个VueJS应用.html
1.下载Vue: https://unpkg.com/vue/dist/vue.js
2.将vue.js拷贝到任意一个目录(工作目录)
3.在同一个目录下用编辑软件(随便什么都行,记事本都可以)新建一个文件,输入以下代码:
<script src="vue.js"></script>
<div id="app">
<p>{{title}}</p>
</div>
<script>
new Vue({
el:"#app",
data:{
title: "Hello World!"
}
});
<script src="vue.js"></script>
<div id="app">
<input type="text" v-on:input="changeTitle">
<p>{{title}}</p>
</div>
<script>
new Vue({
el: "#app",
data: {
title: "Hello World!"
},
methods: {
changeTitle:function (event) {
this.title = event.target.value;
}
}
});
</script>
<script src="vue.js"></script>
<div id="app">
<!-- 注意此处并没有调用Vue模板,而是调用了一个函数 -->
<p>{{sayHello()}}</p>
</div>
<script>
new Vue({
el: "#app",
data: {
title: "Hello World!"
},
methods: {
//此处sayHello是一个方法(函数),但它返回的内容被传送到模版里去了
sayHello:function (event) {
return 'Hello!';
}
}
});
</script>
<script src="vue.js"></script>
<div id="app">
<p>{{sayHello()}}</p>
</div>
<script>
new Vue({
el: "#app",
data: {
title: "Hello World!"
},
methods: {
sayHello:function (event) {
//注意此处,return的是Hello World!
//原生的JS是不允许这么调用的,Vue在中间层做了调剂
return this.title;
}
}
});
</script>
<script src="vue.js"></script>
<div id="app">
<!-- 注意:此处不能用<a href="{{link}}"> 这种形式来传递超链接值,只能用v-bind绑定并设置href的值 -->
<p>{{sayHello()}} - <a v-bind:href="link">Baidu</a> </p>
</div>
<script>
new Vue({
el: "#app",
data: {
title: "Hello World!",
link:"http://baidu.com"
},
methods: {
sayHello:function () {
return this.title;
}
}
});
</script>
<script src="vue.js"></script>
<div id="app">
<!-- 注意此处的v-once -->
<h1 v-once>{{title}}</h1>
<p>{{sayHello()}}</p>
</div>
<script>
new Vue({
el: "#app",
data: {
title: "Hello World!",
},
methods: {
sayHello:function () {
this.title = 'Hello';
return this.title;
}
}
});
</script>
<script src="vue.js"></script>
<div id="app">
<!-- 注意此处的v-once -->
<h1 v-once>{{title}}</h1>
<p>{{sayHello()}}</p>
<!-- 注意:v-html指令让finishedLink以渲染后的HTML格式输出,而不是纯文本
如果以花括号{{finishedLink}} 来表示的话,将会是一个HTML形式的纯文本。
-->
<p v-html = "finishedLink" ></p>
</div>
<script>
new Vue({
el: "#app",
data: {
title: "Hello World!",
finishedLink:'<a href="http://baidu.com">Baidu.com</a>',
},
methods: {
sayHello:function () {
this.title = 'Hello';
return this.title;
}
}
});
</script>
<script src="vue.js"></script>
<div id="app">
<p>I am {{name}}</h1>
<p>I am {{age}} years old.</p>
</div>
<script>
new Vue({
el: "#app",
data: {
name: "Rockage",
age: "40",
}
});
</script>
<script src="vue.js"></script>
<div id="app">
<p>I am {{name}}</p>
<p>I am {{age * 3}} years old.</p>
</div>
<script>
new Vue({
el: "#app",
data: {
name: "Rockage",
age: "40",
}
});
</script>
<script src="vue.js"></script>
<div id="app">
<p>The Random Number is : {{sayRnd()}}</p>
</div>
<script>
new Vue({
el: "#app",
methods: {
sayRnd: function () {
// random_number = Math.random(); // 产生一个0到1的随机数
// random_number = random_number.toFixed(2) //保留两位小数
// 产生一个1到100的随机数
random_number = Math.floor(Math.random() * (100 - 1 + 1)) + 1
return random_number;
}
}
});
</script>
<script src="vue.js" xmlns:v-bind="http://www.w3.org/1999/xhtml"></script>
<div id="app">
<img v-bind:src = "url">
</div>
<script>
new Vue({
el: "#app",
data: {
url: "http://img.mp.itc.cn/upload/20170217/1f650c2645c541ad8cc70842d7d0bbe5_th.jpeg"
}
});
</script>
<script src="vue.js" xmlns:v-bind="http://www.w3.org/1999/xhtml"></script>
<div id="app">
Name <input type = "text" v-bind:value = "default_name" />
</div>
<script>
new Vue({
el: "#app",
data: {
default_name: "Hua Yang"
}
});
</script>
<script src="vue.js"></script>
<div id="app">
<button v-on:click="increase">Click Me</button>
<p>{{ counter}}</p>
</div>
<script>
new Vue({
el: "#app",
data: {
counter: 0,
x: 0,
y: 0
},
methods: {
increase: function () {
this.counter++;
}
},
});
</script>
<script src="vue.js"></script>
<div id="app">
<p v-on:mousemove="updateCoordinates">Coordonates : {{x}}/{{y}}</p>
</div>
<script>
new Vue({
el: "#app",
data: {
counter: 0,
x: 0,
y: 0
},
methods: {
updateCoordinates: function (event) {
this.x = event.clientX;
this.y = event.clientY;
}
},
});
</script>
<script src="vue.js"></script>
<div id="app">
<!--
请注意, 调用increase时增加了两个参数
-->
<button v-on:click="increase(2,$event)">Click Me</button>
<p>{{ counter}}</p>
</div>
<script>
new Vue({
el: "#app",
data: {
counter: 0,
x: 0,
y: 0
},
methods: {
// increase 函数用step和event接收参数
increase: function (step,event) {
this.counter += step;
}
},
});
</script>
HTML部分:
<span v-on:mousemove = "dummy">DEAD SPOT</span>
JS部分:
dummy: function(){
event.stopPropagation();
}
以上代码确保事件不会传播给绑定有这个属性的SPAN上,当然,我们还有更简单的方法,就是使用事件修饰符,使用stop修饰符即可实现这个目的:
<script src="vue.js"></script>
<div id="app">
<p v-on:mousemove="updateCoordinates">Coordonates : {{x}}/{{y}}
<!-- 请注意下面这个SPAN绑定的事件mousemove
采用了.stop修饰符,表示此元素的mousemove事件不做任何处理
-->
- <span v-on:mousemove.stop = "">DEAD SPOT</span>
</p>
</div>
<script>
new Vue({
el: "#app",
data: {
counter: 0,
x: 0,
y: 0
},
methods: {
updateCoordinates: function (event) {
this.x = event.clientX;
this.y = event.clientY;
}
},
});
</script>
<script src="vue.js"></script>
<div id="app">
<input type = "text" v-on:keyup.enter="alertMe" />
</div>
<script>
new Vue({
el: "#app",
data: {
counter: 0,
x: 0,
y: 0
},
methods: {
alertMe: function () {
alert("Alert!");
}
},
});
</script>
<script src="vue.js"></script>
<div id="app">
<button v-on:click="alertMe">Show Alert</button>
</div>
<script>
new Vue({
el: "#app",
data: {
counter: 0,
x: 0,
y: 0
},
methods: {
alertMe: function () {
alert("You Clicked me!");
}
},
});
</script>
<script src="vue.js"></script>
<div id="app">
<input v-on:keydown = "myValue = $event.target.value" type="text"/>
<p>{{myValue}}</p>
</div>
<script>
new Vue({
el: "#app",
data: {
myValue: ''
}
});
</script>
<script src="vue.js"></script>
<div id="app">
<input v-on:keydown.enter = "myValue = $event.target.value" type="text"/>
<p>{{myValue}}</p>
</div>
<script>
new Vue({
el: "#app",
data: {
myValue: ''
}
});
</script>
<script src="vue.js"></script>
<div id="app">
<!-- 此处取消了事件函数,直接用counter++代替 -->
<button v-on:click="counter++">Click Me</button>
<!-- 此处直接修改模板counter的值 -->
<p>{{ counter * 2}}</p>
<!-- 此处是一个三元表达式,用以判断counter的值 -->
<p>{{ counter * 2 > 10 ? 'Greate than 10' : 'Smaller than 10'}}</p>
</div>
<script>
new Vue({
el: "#app",
data: {
counter: 0
}
});
</script>
<script src="vue.js"></script>
<div id="app">
<input type = "text" v-model = "name">
<p>{{name}}</p>
</div>
<script>
new Vue({
el: "#app",
data: {
name: ''
}
});
</script>
<script src="vue.js"></script>
<div id="app">
<button v-on:click="counter1++">Increase Counter 1</button>
<button v-on:click="counter1--">Decrease Counter 1</button>
<button v-on:click="counter2++">Increase Counter 2</button>
<p>Counter:{{counter1}} | {{counter2}}</p>
<!-- 注意两种调用方法是不同的 -->
<p>Counter 1 Result: {{result()}} | {{output}}</p>
</div>
<script>
new Vue({
el: "#app",
data: {
counter1: 0,
counter2: 0
},
computed: {
output: function () {
console.log('Here is Computed')
return this.counter1 > 5 ? "Greater than 5" : "Smaller than 5"
}
},
methods: {
result: function () {
console.log('Here is Methods')
return this.counter1 > 5 ? "Greater than 5" : "Smaller than 5"
}
}
});
</script>
<!-- 作业3问题:响应式属性 - 作业1 -->
<script src="vue.js"></script>
<div id="app">
<button v-on:click="value += 5">Add 5</button>
<button v-on:click="value += 1">Add 1</button>
<p>{{result}}</p>
</div>
<script>
new Vue({
el: "#app",
data: {
value: 0,
},
computed: {
result: function () {
return this.value == 37 ? "Done" : "Not there yet"
}
}
});
</script>
<script src="vue.js"></script>
<div id="app">
<button v-on:click="value += 5">Add 5</button>
<button v-on:click="value += 1">Add 1</button>
<p>Current Value:{{value}} </p>
<p>{{result}}</p>
</div>
<script>
new Vue({
el: "#app",
data: {
value: 0
},
computed: {
result: function () {
return this.value == 37 ? "Done" : "Not there yet"
}
},
watch: {
result: function () { //watch可以监听computed里的属性
var vm = this;
setTimeout(function () {
vm.value = 0
// 但无法修改computed里定义的属性,即如果写成 vm.result = "XXX" 则程序会报错
}, 5000)
}
}
});
</script>
<style>
.demo {
width: 100px;
height: 100px;
background-color: gray;
display: inline-block;
margin: 10px;
}
.red {
background-color: red;
}
}
</style>
<script src="vue.js"></script>
<div id="app">
<div
class="demo"
@click="attachRed = !attachRed"
:class="{red: attachRed}"
></div>
</div>
<script>
new Vue({
el: "#app",
data: {
attachRed: false
}
});
</script>
<style>
.demo {
width: 100px;
height: 100px;
background-color: gray;
display: inline-block;
margin: 10px;
}
.red {
background-color: red;
}
.blue {
background-color: blue;
}
</style>
<script src="vue.js"></script>
<div id="app">
<div
class="demo"
@click="attachRed = !attachRed"
:class="divClasses"
></div>
</div>
<script>
new Vue({
el: "#app",
data: {
attachRed: false
},
computed: {
divClasses: function () {
return {
red: this.attachRed,
blue: !this.attachRed
}
}
}
});
</script>
<!-- 033-CSS类动态样式-使用命名 -->
<style>
.demo {
width: 100px;
height: 100px;
background-color: gray;
display: inline-block;
margin: 10px;
}
.red {
background-color: red;
}
.blue {
background-color: blue;
}
.green {
background-color: green;
}
</style>
<script src="vue.js"></script>
<div id="app">
<div
class="demo"
@click="attachRed = !attachRed"
:class="divClasses"
></div>
<div
class="demo"
:class="[color,{red: attachRed}]"
></div>
<hr>
<!-- 此处输入框双向绑定了color属性,即键盘输入的内容会即时作为CSS类名传到HTML中去 -->
<input type = "text" v-model = "color">
</div>
<script>
new Vue({
el: "#app",
data: {
attachRed: false,
color:'green'
//color属性默认为green,请注意由于双向绑定的原因,green这个字符串也会同时传递到输入框里
},
computed: {
divClasses: function () {
return {
red: this.attachRed,
blue: !this.attachRed
}
}
}
});
</script>
<div class="demo" :style="{'background-color':color}"></div>
data: { color: 'grey', width: 100}
<input type="text" v-model="color">
<!-- 章节2课时34-动态设置样式(不使用CSS类) -->
<style>
.demo {
width: 100px;
height: 100px;
background-color: gray;
display: inline-block;
margin: 10px;
}
</style>
<script src="vue.js"></script>
<div id="app">
<div class="demo" :style="{'background-color':color}"></div>
<div class="demo" :style="myStyle"></div>
<hr>
<input type="text" v-model="color">
<input type="text" v-model="width">
</div>
<script>
new Vue({
el: "#app",
data: {
color: 'grey',
width: 100
},
computed: {
myStyle: function () {
return {
backgroundColor: this.color,
width: this.width + 'px'
}
}
}
});
</script>
作为程序员的我们,经常要用到文件的上传和下载功能。到了需要用的时候,各种查资料。有木有..有木有...。为了方便下次使用,这里来做个总结和备忘。
最原始、最简单、最粗暴的文件上传。
前端代码:
//方式1
<form action="/Home/SaveFile1" method="post" enctype="multipart/form-data">
<input type="file" class="file1" name="file1" />
<button type="submit" class="but1">上传</button>
</form>
【注意】
后台代码:
public ActionResult SaveFile1()
{
if (Request.Files.Count > 0)
{
Request.Files[0].SaveAs(Server.MapPath("~/App_Data/") + Request.Files[0].FileName);
return Content("保存成功");
}
return Content("没有读到文件");
}
虽然上面的方式简单粗暴,但是不够友好。页面必然会刷新。难以实现停留在当前页面,并给出文件上传成功的提示。
随着时间的流逝,技术日新月异。ajax的出现,使得异步文件提交变得更加容易。
下面我们利用jquery.form插件来实现文件的异步上传。
首先我们需要导入jquery.js和jquery.form.js
前端代码:
<form id="form2" action="/Home/SaveFile2" method="post" enctype="multipart/form-data">
<input type="file" class="file1" name="file1" />
<button type="submit" class="but1">上传1</button>
<button type="button" class="but2">上传2</button>
</form>
//方式2(通过ajaxForm绑定ajax操作)
$(function () {
$('#form2').ajaxForm({
success: function (responseText) {
alert(responseText);
}
});
});
//方式3(通过ajaxSubmit直接执行ajax操作)
$(function () {
$(".but2").click(function () {
$('#form2').ajaxSubmit({
success: function (responseText) {
alert(responseText);
}
});
});
});
后台代码:
public string SaveFile2()
{
if (Request.Files.Count > 0)
{
Request.Files[0].SaveAs(Server.MapPath("~/App_Data/") + Path.GetFileName(Request.Files[0].FileName));
return "保存成功";
}
return "没有读到文件";
}
原理:
我们很多时候使用了插件,就不管其他三七二十一呢。
如果有点好奇心,想想这个插件是怎么实现的。随便看了看源码一千五百多行。我的妈呀,不就是个异步上传的吗,怎么这么复杂。
难以看出个什么鬼来,直接断点调试下吧。
原来插件内部有iframe和FormData不同方式来上传,来适应更多版本浏览器。
iframe这东西太恶心。我们看到上面可以利用FormData来上传文件,这个是Html 5 才有的。下面我们自己也来试试吧。
前端代码:
<input id="fileinfo" type="file" class="notFormFile" />
<button type="button" class="btnNotForm">上传4</button>
//方式4
$(".btnNotForm").click(function () {
var formData = new FormData();//初始化一个FormData对象
formData.append("files", $(".notFormFile")[0].files[0]);//将文件塞入FormData
$.ajax({
url: "/Home/SaveFile2",
type: "POST",
data: formData,
processData: false, // 告诉jQuery不要去处理发送的数据
contentType: false, // 告诉jQuery不要去设置Content-Type请求头
success: function (responseText) {
alert(responseText);
}
});
});
后面的代码:(不变,还是上例代码)
public string SaveFile2()
{
if (Request.Files.Count > 0)
{
Request.Files[0].SaveAs(Server.MapPath("~/App_Data/") + Path.GetFileName(Request.Files[0].FileName));
return "保存成功";
}
return "没有读到文件";
}
我们看到,FormData对象也只是在模拟一个原始的表单格式的数据。那有没有可能利用表单或表单格式来上传文件呢?答案是肯定的。(下面马上揭晓)
前端代码:
<input type="file" id="file5" multiple>
<button type="button" class="btnFile5">上传5</button>
//方式5
$(".btnFile5").click(function () {
$.ajax({
url: "/Home/SaveFile4",
type: "POST",
data: $("#file5")[0].files[0],
processData: false, // 告诉jQuery不要去处理发送的数据
contentType: false, // 告诉jQuery不要去设置Content-Type请求头
success: function (responseText) {
alert(responseText);
}
});;
});
后台代码:
public string SaveFile4()
{
//这里发现只能得到一个网络流,没有其他信息了。(比如,文件大小、文件格式、文件名等)
Request.SaveAs(Server.MapPath("~/App_Data/SaveFile4.data") + "", false);
return "保存成功";
}
细心的你发现没有了表单格式,我们除了可以上传文件流数据外,不能再告诉后台其他信息了(如文件格式)。
到这里,我似乎明白了以前上传文件为什么非得要用个form包起来,原来这只是和后台约定的一个传输格式而已。
其实我们单纯地用jq的ajax传输文本数据的时候,最后也是组装成了form格式的数据,如:
$.ajax({
data: { "userName": "张三" }
在知道了上面的各种上传之后,我们是不是就满于现状了呢?no,很多时候我们需要传输大文件,一般服务器都会有一定的大小限制。
某天,你发现了一个激情小电影想要分享给大家。无奈,高清文件太大传不了,怎么办?我们可以化整为零,一部分一部分的传嘛,也就是所谓的分片上传。
前端代码:
<input type="file" id="file6" multiple>
<button type="button" class="btnFile6">分片上传6</button>
<div class="result"></div>
//方式6
$(".btnFile6").click(function () {
var upload = function (file, skip) {
var formData = new FormData();//初始化一个FormData对象
var blockSize = 1000000;//每块的大小
var nextSize = Math.min((skip + 1) * blockSize, file.size);//读取到结束位置
var fileData = file.slice(skip * blockSize, nextSize);//截取 部分文件 块
formData.append("file", fileData);//将 部分文件 塞入FormData
formData.append("fileName", file.name);//保存文件名字
$.ajax({
url: "/Home/SaveFile6",
type: "POST",
data: formData,
processData: false, // 告诉jQuery不要去处理发送的数据
contentType: false, // 告诉jQuery不要去设置Content-Type请求头
success: function (responseText) {
$(".result").html("已经上传了" + (skip + 1) + "块文件");
if (file.size <= nextSize) {//如果上传完成,则跳出继续上传
alert("上传完成");
return;
}
upload(file, ++skip);//递归调用
}
});
};
var file = $("#file6")[0].files[0];
upload(file, 0);
});
后台代码:
public string SaveFile6()
{
//保存文件到根目录 App_Data + 获取文件名称和格式
var filePath = Server.MapPath("~/App_Data/") + Request.Form["fileName"];
//创建一个追加(FileMode.Append)方式的文件流
using (FileStream fs = new FileStream(filePath, FileMode.Append, FileAccess.Write))
{
using (BinaryWriter bw = new BinaryWriter(fs))
{
//读取文件流
BinaryReader br = new BinaryReader(Request.Files[0].InputStream);
//将文件留转成字节数组
byte[] bytes = br.ReadBytes((int)Request.Files[0].InputStream.Length);
//将字节数组追加到文件
bw.Write(bytes);
}
}
return "保存成功";
}
相对而言,代码量多了一点,复杂了一点。不过相对于网上的其他分片上传的代码应该要简单得多(因为这里没有考虑多文件块同时上传、断点续传。那样就需要在后台把文件块排序,然后上传完成按序合并,然后删除原来的临时文件。有兴趣的同学可以自己试试,稍候在分析上传插件webuploader的时候也会实现)。
效果图:
【说明】:如果我们想要上传多个文件怎么办?其实H5中也提供了非常简单的方式。直接在input里面标记multiple,<input type="file" id="file6" multiple>,然后我们后台接收的也是一个数组Request.Files。
只能说H5真是强大啊,权限越来越大,操作越来越牛逼。
前端代码(拖拽上传):
<textarea class="divFile7" style="min-width:800px;height:150px" placeholder="请将文件拖拽或直接粘贴到这里"></textarea>
//方式7
$(".divFile7")[0].ondrop = function (event) {
event.preventDefault();//不要执行与事件关联的默认动作
var files = event.dataTransfer.files;//获取拖上来的文件
//以下代码不变
var formData = new FormData();//初始化一个FormData对象
formData.append("files", files[0]);//将文件塞入FormData
$.ajax({
url: "/Home/SaveFile2",
type: "POST",
data: formData,
processData: false, // 告诉jQuery不要去处理发送的数据
contentType: false, // 告诉jQuery不要去设置Content-Type请求头
success: function (responseText) {
alert(responseText);
}
});
};
后台代码:
略(和之前的SaveFile2一样)
前端代码(粘贴上传 限图片格式):
//方式8
$(".divFile7")[0].onpaste = function (event) {
event.preventDefault();//不要执行与事件关联的默认动作
var clipboard = event.clipboardData.items[0];//剪贴板数据
if (clipboard.kind == 'file' || clipboard.type.indexOf('image') > -1) {//判断是图片格式
var imageFile = clipboard.getAsFile();//获取文件
//以下代码不变
var formData = new FormData;
formData.append('files', imageFile);
formData.append('fileName', "temp.png");//这里给文件命个名(或者直接在后台保存的时候命名)
$.ajax({
url: "/Home/SaveFile8",
type: "POST",
data: formData,
processData: false, // 告诉jQuery不要去处理发送的数据
contentType: false, // 告诉jQuery不要去设置Content-Type请求头
success: function (responseText) {
alert(responseText);
}
});
}
};
后台代码:
public string SaveFile8()
{
//保存文件到根目录 App_Data + 获取文件名称和格式
var filePath = Server.MapPath("~/App_Data/") + Request.Form["fileName"];
if (Request.Files.Count > 0)
{
Request.Files[0].SaveAs(filePath);
return "保存成功";
}
return "没有读到文件";
}
效果图:
已经列举分析了多种上传文件的方式,我想总有一种适合你。不过,上传这个功能比较通用,而我们自己写的可能好多情况没有考虑到。接下来简单介绍下百度的WebUploader插件。
比起我们自己写的简单上传,它的优势:稳定、兼容性好(有flash切换,所以支持IE)、功能多、并发上传、断点续传(主要还是靠后台配合)。
官网:http://fex.baidu.com/webuploader/
插件下载:https://github.com/fex-team/webuploader/releases/download/0.1.5/webuploader-0.1.5.zip
下面开始对WebUploader的使用
第一种,简单粗暴
前端代码:
<div id="picker">选择文件</div>
<button id="ctlBtn" class="btn btn-default">开始上传</button>
<!--引用webuploader的js和css-->
<link href="~/Scripts/webuploader-0.1.5/webuploader.css" rel="stylesheet" />
<script src="~/Scripts/webuploader-0.1.5/webuploader.js"></script>
<script type="text/javascript">
var uploader = WebUploader.create({
// (如果是新浏览器 可以不用 flash)
//swf: '/Scripts/webuploader-0.1.5/Uploader.swf',
// 文件接收服务端。
server: '/Webuploader/SaveFile',
// 选择文件的按钮。可选。
// 内部根据当前运行是创建,可能是input元素,也可能是flash.
pick: '#picker'
});
$("#ctlBtn").click(function () {
uploader.upload();
});
uploader.on('uploadSuccess', function (file) {
alert("上传成功");
});
</script>
后台代码:
public string SaveFile()
{
if (Request.Files.Count > 0)
{
Request.Files[0].SaveAs(Server.MapPath("~/App_Data/") + Path.GetFileName(Request.Files[0].FileName));
return "保存成功";
}
return "没有读到文件";
}
第二种,分片上传。和我们之前自己写的效果差不多。
前端代码:
var uploader = WebUploader.create({
//兼容老版本IE
swf: '/Scripts/webuploader-0.1.5/Uploader.swf',
// 文件接收服务端。
server: '/Webuploader/SveFile2',
// 开起分片上传。
chunked: true,
//分片大小
chunkSize: 1000000,
//上传并发数
threads: 1,
// 选择文件的按钮。
pick: '#picker'
});
// 点击触发上传
$("#ctlBtn").click(function () {
uploader.upload();
});
uploader.on('uploadSuccess', function (file) {
alert("上传成功");
});
后台代码:
public string SveFile2()
{
//保存文件到根目录 App_Data + 获取文件名称和格式
var filePath = Server.MapPath("~/App_Data/") + Path.GetFileName(Request.Files[0].FileName);
//创建一个追加(FileMode.Append)方式的文件流
using (FileStream fs = new FileStream(filePath, FileMode.Append, FileAccess.Write))
{
using (BinaryWriter bw = new BinaryWriter(fs))
{
//读取文件流
BinaryReader br = new BinaryReader(Request.Files[0].InputStream);
//将文件留转成字节数组
byte[] bytes = br.ReadBytes((int)Request.Files[0].InputStream.Length);
//将字节数组追加到文件
bw.Write(bytes);
}
}
return "保存成功";
}
我们看到了有个参数threads: 1上传并发数,如果我们改成大于1会怎样?前端会同时发起多个文件片上传。后台就会报错,多个进程同时操作一个文件。
那如果我们想要多线程上传怎么办?改代码吧(主要是后台逻辑)。
前端代码:
//并发上传(多线程上传)
var uploader = WebUploader.create({
//兼容老版本IE
swf: '/Scripts/webuploader-0.1.5/Uploader.swf',
// 文件接收服务端。
server: '/Webuploader/SveFile3',
// 开起分片上传。
chunked: true,
//分片大小
chunkSize: 1000000,
//上传并发数
threads: 10,
// 选择文件的按钮。
pick: '#picker'
});
// 点击触发上传
$("#ctlBtn").click(function () {
uploader.upload();
});
uploader.on('uploadSuccess', function (file) {
//上传完成后,给后台发送一个合并文件的命令
$.ajax({
url: "/Webuploader/FileMerge",
data: { "fileName": file.name },
type: "post",
success: function () {
alert("上传成功");
}
});
});
后台代码:
public string SveFile3()
{
var chunk = Request.Form["chunk"];//当前是第多少片
var path = Server.MapPath("~/App_Data/") + Path.GetFileNameWithoutExtension(Request.Files
if (!Directory.Exists(path))//判断是否存在此路径,如果不存在则创建
{
Directory.CreateDirectory(path);
}
//保存文件到根目录 App_Data + 获取文件名称和格式
var filePath = path + "/" + chunk;
//创建一个追加(FileMode.Append)方式的文件流
using (FileStream fs = new FileStream(filePath, FileMode.Append, FileAccess.Write))
{
using (BinaryWriter bw = new BinaryWriter(fs))
{
//读取文件流
BinaryReader br = new BinaryReader(Request.Files[0].InputStream);
//将文件留转成字节数组
byte[] bytes = br.ReadBytes((int)Request.Files[0].InputStream.Length);
//将字节数组追加到文件
bw.Write(bytes);
}
}
return "保存成功";
}
/// <summary>
/// 合并文件
/// </summary>
/// <param name="path"></param>
/// <returns></returns>
public bool FileMerge()
{
var fileName = Request.Form["fileName"];
var path = Server.MapPath("~/App_Data/") + Path.GetFileNameWithoutExtension(fileName);
//这里排序一定要正确,转成数字后排序(字符串会按1 10 11排序,默认10比2小)
foreach (var filePath in Directory.GetFiles(path).OrderBy(t => int.Parse(Path.GetFileNameWithoutExtension(t))))
{
using (FileStream fs = new FileStream(Server.MapPath("~/App_Data/") + fileName, FileMode.Append, FileAccess.Write))
{
byte[] bytes = System.IO.File.ReadAllBytes(filePath);//读取文件到字节数组
fs.Write(bytes, 0, bytes.Length);//写入文件
}
System.IO.File.Delete(filePath);
}
Directory.Delete(path);
return true;
}
到这里你以为就结束了吗?错,还有好多情况没有考虑到。如果多个用户上传的文件名字一样会怎样?如何实现断点续传?还没实现选择多个文件?不过,这里不打算继续贴代码了(再贴下去,代码量越来越多了),自己也来练习练习吧。
提供一个思路,上传前先往数据库插入一条数据。数据包含文件要存的路径、文件名(用GUID命名,防止同名文件冲突)、文件MD5(用来识别下次续传和秒传)、临时文件块存放路径、文件是否完整上传成功等信息。
然后如果我们断网后再传,首先获取文件MD5值,看数据库里面有没上传完成的文件,如果有就实现秒传。如果没有,看是不是有上传了部分的。如果有接着传,如果没有则重新传一个新的文件。
之前我一直很疑惑,为什么上传文件一定要用form包起来,现在算是大概明白了。
最开始在javascript还不流行时,我们就可以直接使用submit按钮提交表单数据了。表单里面可以包含文字和文件。然后随着js和ajax的流行,可以利用ajax直接异步提交部分表单数据。这里开始我就纠结了,为什么ajax可以提交自己组装的数据。那为什么不能直接提交文件呢。这里我错了,ajax提交的并不是随意的数据,最后还是组装成了表单格式(因为后台技术对表单格式数据的支持比较普及)。但是现有的技术还不能通过js组装一个文件格式的表单数据。直到H5中的FormData出现,让前端js组装一个包含文件的表单格式数据成为了可能。所以说表单只是为了满足和后台“约定”的数据格式而已。
相关推荐
demo
*请认真填写需求信息,我们会在24小时内与您取得联系。