最原始的方式:

前端代码:

    <div>
<span>最原始的方式</span><br />
<span>条件1:必须是 post 方式</span><br />
<span>条件2:必须注明是传输文件 enctype="multipart/form-data"</span><br />
<span>条件3:必须设置name属性,name="myFile"</span><br />
<form id="myForm1" method="post" enctype="multipart/form-data" action="http://localhost:42561/api/upload/upload">
<input type="file" name="myFile" />
<input type="submit" value="原始form表单上传文件" />
</form>
</div>

后台代码:

        public async Task<HttpResponseMessage> Upload()
{
var files = HttpContext.Current.Request.Files;
var path = HttpContext.Current.Server.MapPath("/img/");
if (files.Count > )
{
foreach (string file in files)
{
//这里的 file ,就是 input[type="file"] 标签的name属性的值,
//这也是为什么上传文件,input[type="file"] 标签必须设置name属性的值的原因之一.
var img = files[file];
if (img?.ContentLength > )
{
var fileName = img.FileName;
await Task.Run(() => img.SaveAs(path + fileName));
}
}
return new HttpResponseMessage(HttpStatusCode.OK);
}
return Request.CreateErrorResponse(HttpStatusCode.BadRequest, "没有文件");
}

利用FormData上传单个文件

前端代码:

    <div>
<span>利用FormData上传单个文件</span><br />
<form id="myForm2">
<input type="file" name="myFile" />
<input type="button" value="利用FormData上传单个文件" onclick="uploadOne()" />
</form>
</div>
        function uploadOne() {
var url = "http://localhost:42561/api/upload/upload"; //这里之所以会写成[0],是因为$(...)是JQ对象,是个数组,而这里需要传入的是JS对象.
var data = new FormData($("#myForm2")[0]);
$.ajax({
url: url,
data: data,
type: "post",
processData: false,//表示提交的时候不会序列化 data,而是直接使用 data,默认为 true
contentType: false,//表示不要去设置Content-Type请求头
cache: false,//设置为 false 将不会从浏览器缓存中加载请求信息。
success: function () { }
});
}

利用FormData上传多个文件

前端代码:

    <div>
<span>利用FormData上传多个文件</span><br />
<form id="myForm3">
<input type="file" id="myFile" multiple />
<input type="button" value="利用FormData上传多个文件" onclick="uploadSome()" />
</form>
</div>
        function uploadSome() {
var url = "http://localhost:42561/api/upload/upload"; var data = new FormData();
var files = $("#myFile")[0].files;
for (var i = 0; i < files.length; i++) {
//这里的 myFile0,myFile1,myFile2就是input type="file" 标签的name属性,所以标签里面可以不用写name属性了
data.append("myFile" + i, $("#myFile")[0].files[i]);
}
$.ajax({
url: url,
data: data,
type: "post",
processData: false,
contentType: false,
cache: false,
success: function () { }
});
}

分片上传

前端代码:

    <div>
<span>分片上传单个文件</span><br />
<form id="myForm4">
<input type="file" id="myFileStep" />
<input type="button" value="分片上传单个文件" onclick="uploadStep()"/>
</form>
<br />
<span class="result"></span>
</div>
   function uploadStep() {
var upload = function (file, skip) {
var data = new FormData();
var blockSize = 1000;
var nextSize = Math.min((skip + 1) * blockSize, file.size);
var fileData = file.slice(skip * blockSize, nextSize);
data.append("myFile", fileData); //由于传输的是二进制数据(fileData),后台(MVC或者Api无法通过files[0].FileName获取文件名
//所以只能通过构造form表单数据传递(键值对形式,fileName=xxx.jpg&aaa=yyy),后台再通过request.Form[fileName]获取
data.append("fileName", file.name);
var url = "http://localhost:42561/api/upload/uploadStep";
$.ajax({
url: url,
type: "POST",
data: data,
processData: false, // 告诉jQuery不要去处理发送的数据
contentType: false, // 告诉jQuery不要去设置Content-Type请求头
success: function () {
$(".result").html("已经上传了" + (skip + 1) + "块文件");
if (file.size <= nextSize) { //如果上传完成,则跳出继续上传
alert("上传完成");
return;
}
upload(file, ++skip); //递归调用
}
});
};
var file = $("#myFileStep")[0].files[0];
upload(file, 0);
}

后台代码:

        public HttpResponseMessage UploadStep()
{
var path = HttpContext.Current.Server.MapPath("/img/");
var name = HttpContext.Current.Request.Form["fileName"];
var filePath = path + name;
//创建一个追加(FileMode.Append)方式的文件流
using (FileStream fs = new FileStream(filePath, FileMode.Append, FileAccess.Write))
{
var file = HttpContext.Current.Request.Files[];
//方法一
using (BinaryWriter bw = new BinaryWriter(fs))
{
//读取文件流
BinaryReader br = new BinaryReader(file.InputStream);
//将文件流转成字节数组
byte[] bytes = br.ReadBytes((int)file.InputStream.Length);
//将字节数组追加到文件
bw.Write(bytes);
br.Dispose();
}
//方法二
//Stream sm = file.InputStream;
//byte[] bytes = new byte[sm.Length];
//sm.Read(bytes, 0, bytes.Length);
//fs.Write(bytes, 0, bytes.Length);
//sm.Dispose();
}
return new HttpResponseMessage(HttpStatusCode.OK);
}

JQ 上传文件(单个,多个,分片)的更多相关文章

  1. springmvc上传文件方法及注意事项

    本文基于注解的配置,敬请留意  基于注解整合 一.springmvc为我们提供两种上传方式配置: org.springframework.web.multipart.commons.CommonsMu ...

  2. C#实现分片上传文件

    using System; using System.Collections.Generic; using System.Linq; using System.Web; using System.IO ...

  3. django实现分片上传文件

    目标:利用django实现上传文件功能 1,先设置路由系统 urls.py from django.conf.urls import url,include from django.contrib i ...

  4. WebUploader分片断点上传文件(二)

    写在前面: 这几天,有去研究一下WebUploader上传文件,前面的博客有记录下使用WebUploader简单上传文件的例子,今天就把分片断点上传的例子也记录下吧,在博客园中,也查看了一些资料,基本 ...

  5. 使用uploadify多文件上传,单个删除上传成功的图片

    总体思路:在用uploadify上传成功一张图片,用js生成相应的元素,放到指定的位置,并且加上删除的标志.在保存的时候,把是img的所有的值,放到对应到字段里. jsp: <tr> &l ...

  6. JQ中的FormData对象 ajax上传文件

    HTML代码: <form enctype="multipart/form-data" method="POST" name="searchfo ...

  7. node.js分片上传文件

    前端 : <html> <head> <title>分片上传文件</title> </head> <body> <div ...

  8. springboot文件上传: 单个文件上传 和 多个文件上传

    单个文件上传 //文件上传统一处理 @RequestMapping(value = "/upload",method=RequestMethod.POST) @ResponseBo ...

  9. 分享一个FileUtil工具类,基本满足web开发中的文件上传,单个文件下载,多个文件下载的需求

    获取该FileUtil工具类具体演示,公众号内回复fileutil20200501即可. package com.example.demo.util; import javax.servlet.htt ...

随机推荐

  1. ssm实现分页查询

    ssm整合实现分页查询 一.通过limit查询语句实现分页,并展示 1.mapper.xml配置 <select id="selectUsersByPage" paramet ...

  2. SpringMVC【开发Controller】详解

    前言 本文主要是讲解在Controller中的开发,主要的知识点有如下: 编码过滤器 使用注解开发 注解@RequestMapping详解 业务方法接收参数 字符串转日期 重定向和转发 返回JSON ...

  3. SpringDataJPA入门就这么简单

    一.SpringData入门 在上次学SpringBoot的时候,那时候的教程就已经涉及到了一点SpringData JPA的知识了.当时还是第一次见,觉得也没什么大不了,就是封装了Hibernate ...

  4. python web开发-flask读取txt文件内容

    某些情况下,需要读取flask网站要目录下的txt文件.但是直接在flask网站的目录下创建一个文件是无法访问的.从网站找了一些资料,最终发现通过写一个方法返回txt内容比较简单方便,不过此方法适用于 ...

  5. 托管ASP.NET Core应用程序到Windows服务中

    由于公司程序前置Nginx反向代理,所以在Windows中部署过程中没有采用IIS托管.Net Core应用,一直采用控制台dotnet命令直接运行.但是测试过程中,发现程序内Session一直无法覆 ...

  6. canvas小球

      小球碰撞效果是采用面向对象的方式写的,在小球的构造器里包含了小球的属性值,大小,移动速度,半径大小以及颜色. 在小球的原型方法里,添加了小球运动的方法,当小球碰撞到屏幕边界的时候进行反弹. 小球是 ...

  7. 最大堆(Java数组实现)

    最大堆 data[1]开始存,data[0]空着不用.也可以把data[0]当成size来用. public class MaxHeap<T extends Comparable<? su ...

  8. [模拟赛] T2 混合图

    Description Hzwer神犇最近又征服了一个国家,然后接下来却也遇见了一个难题. Hzwer的国家有n个点,m条边,而作为国王,他十分喜欢游览自己的国家.他一般 会从任意一个点出发,随便找边 ...

  9. 【Django】 rest-framework和RestfulAPI的设计

    [rest-framework] 这是一个基于django才能发挥作用的组件,专门用于构造API的. 说到API,之前在其他项目中我也做过一些小API,不过那些都是玩票性质,结构十分简单而且要求的设计 ...

  10. 【Windows】定时任务设置

    Windows定时任务 linux上面的定时任务已经解除过好多次了.不外乎crontab,at之类的命令,而windows上的定时任务今天才偶尔看到怎么设置.想到以后生活上可能会用到一些这方面的知识就 ...