图片预览(base64和blob:图片链接)和ajax上传、下载(带进度提示)
直接上代码
html和js
<!DOCTYPE html> <html>
<head>
<meta name="viewport" content="width=device-width" />
<title>Index</title>
<style>
fieldset {
width: 400px;
height: 150px;
} .uploadImg {
width: 40px;
height: 40px;
} a {
padding: 10px;
text-decoration: none;
border: 2px solid #e27b32;
position: relative;
top: 17px;
left: 24%;
color: #d46c6c;
border-radius: 18px;
} .outputContain {
width: 400px;
height: 56px;
overflow-x: auto;
overflow-y: hidden;
}
</style>
</head>
<body>
<fieldset>
<legend>上传图片-获取图片</legend>
<div class="contain">
<form enctype="multipart/form-data" method="post" name="form">
<input type="file" id="file" name="file" multiple="multiple" />
</form>
<div id="progress"></div>
<div class="outputContain">
<div id="output"></div>
</div>
<a href="javascript:clear()">清空所有</a>
<a href="javascript:uploadFile()">上传文件</a>
</div>
</fieldset> <a href="javascript:testReq()">测试请求</a> <script>
'use strict' var progressTip = document.getElementById('progress'),
outPutTip = document.getElementById('output'),
fileInput = document.getElementById('file'); //ajax+FormData上传文件
function uploadFile() {
var formData = new FormData(document.forms.namedItem('form'));
var needResult = 0;
formData.append('needResult', needResult);
var xhr = new XMLHttpRequest();
xhr.open('post', '/home/upload', true);
xhr.setRequestHeader('testHeader', 'testHeader');
xhr.timeout = 60 * 1000;
xhr.ontimeout = function (event) {
progressTip.innerHTML = '超时(60s)';
} xhr.onload = function (event) {
progressTip.innerHTML = '上传完成';
if (this.status === 200) {
//needResult == 1 && this.responseText.toString().split('|').forEach(function (url) {
// getImg(url);
//});
} else {
progressTip.innerHTML = 'error:状态码:' + this.status + ' 错误消息:' + this.statusText;
}
} xhr.upload.onprogress = function (event) {
if (event.lengthComputable) {
var pro = ((event.loaded / event.total).toFixed(4) * 100).toFixed(2);
progressTip.innerHTML = '上传进度:' + pro + '%<br/>';
}
} xhr.send(formData);
} //ajax下载文件
function getImg(url) {
var xhr = new XMLHttpRequest();
xhr.open('get', url, true);
xhr.responseType = 'blob';
xhr.onload = function (e) {
if (this.status === 200) {
getFileReaderResult(this.response, function (result) {
appendImgToBox(result);
});
} else {
progressTip.innerHTML = '发生错误';
}
}
xhr.send();
} //返回blog:图片链接的预览
function getFileUrl(file) {
var src = window.URL.createObjectURL(file);
return src || '';
} //FileReader读取文件,返回base64的图片
function getFileReaderResult(blob, callback) {
var fileReader = new FileReader();
fileReader.readAsDataURL(blob);
fileReader.onprogress = function (event) {
if (event.lengthComputable) {
var pro = ((event.loaded / event.total).toFixed(4) * 100).toFixed(2);
progressTip.innerHTML = '预览进度:' + pro + '%<br/>';
}
}
fileReader.onloadend = function () {
progressTip.innerHTML = '预览完成';
typeof callback === 'function' && callback(this.result);
}
} //添加一个预览图到预览列表里面
function appendImgToBox(src) {
outPutTip.innerHTML += '<image class="uploadImg" src="' + src + '"/>';
var imgCount = document.getElementsByClassName('uploadImg').length,
singleImgWidth = document.getElementsByClassName('uploadImg')[0].offsetWidth;
outPutTip.style.width = imgCount * singleImgWidth + 'px';
} //重置页面
function clear() {
outPutTip.innerHTML = '';
outPutTip.style.width = '0px';
fileInput.value = '';
} //选择文件后生产预览图
fileInput.addEventListener('change', function (e) {
for (var i = 0; i < e.target.files.length; i++) {
getFileReaderResult(e.target.files[i], function (result) {
appendImgToBox(result);
});
}
}); function testReq() {
var xhr = new XMLHttpRequest();
xhr.open('post', '/home/add', true);
xhr.onprogress = function (e) {
console.log(e);
}
xhr.upload.onprogress = function (e) {
console.log(e);
} xhr.onload = function () {
if (this.status == 200) {
if (this.readyState == 4) {
alert('完成');
}
}
}
xhr.send();
} </script>
</body>
</html>
C#后台接收上传的文件
public string Upload()
{
HttpFileCollectionBase files = Request.Files;
string dirName = "Upload";
string saveDir = Server.MapPath("~/" + dirName + "/");
if (!Directory.Exists(saveDir)) Directory.CreateDirectory(saveDir);
List<string> uploadedFiles = new List<string>();
string baseUrl = Request.Url.Scheme + "://" + Request.Url.Host + ":" + Request.Url.Port + "/";
for (int i = ; i < files.Count; i++)
{
HttpPostedFileBase file = files[i];
if (file.ContentLength == ) continue;
FileInfo fileInfo = new FileInfo(file.FileName);
string fileName = Guid.NewGuid().ToString("N") + fileInfo.Extension,
savePath = Path.Combine(saveDir, fileName);
file.SaveAs(savePath); uploadedFiles.Add(baseUrl + dirName + "/" + fileName);
} return Request.Form["needResult"] == "" ? string.Join("|", uploadedFiles) : string.Empty;
}
预览来一发:
图片预览(base64和blob:图片链接)和ajax上传、下载(带进度提示)的更多相关文章
- 支持多文件上传,预览,拖拽,基于bootstra的上传插件fileinput 的ajax异步上传
首先需要导入一些js和css文件 <link href="__PUBLIC__/CSS/bootstrap.css" rel="stylesheet"&g ...
- 支持多文件上传,预览,拖拽,基于bootstrap的上传插件fileinput 的ajax异步上传(转载)
首先需要导入一些js和css文件 <link href="__PUBLIC__/CSS/bootstrap.css" rel="stylesheet"&g ...
- 如何使用JavaScript直接上传并预览粘贴板的图片?
(题图:梵高-橄榄树) 提出需求 因为工作原因,现在有一个需求就是需要用户使用QQ或者微信复制一张截图后,在div中直接粘贴这张图片,而不是采用上传的方式.类似我们在使用QQ微信时直接粘贴截图的操作, ...
- js实现移动端图片预览:手势缩放, 手势拖动,双击放大...
.katex { display: block; text-align: center; white-space: nowrap; } .katex-display > .katex > ...
- JS实现图片预览与等比缩放
案例仅为图片预览功能,省略图片上传步骤,框架为easyui. HTML代码: @*text-align:center;水平居中 vertical-align: middle;display: tabl ...
- vue项目中图片预览旋转功能
最近项目中需要在图片预览时,可以旋转图片预览,在网上找了下,发现有一款功能强大的图片组件:viewerjs. git-hup: https://github.com/fengyuanchen/view ...
- 浅谈js本地图片预览
最近在工作中遇到一个问题,就是实现一个反馈页面,这个反馈页面的元素有反馈主题.反馈类型.反馈内容.反馈人联系电话以及反馈图片.前端将这些反馈的元素POST给后台提供的接口:实现这个工作的步骤就是:页面 ...
- HTML5浏览器端图片预览&生成Base64
本文主要介绍如何通过拖拽方式在浏览器端实现图片预览,并生成图片的Base64编码. 工具链接:图片转Base64. 首先介绍一下FileReader, FileReader对象允许浏览器使用File或 ...
- 本地与在线图片转Base64及图片预览
查看效果:http://sandbox.runjs.cn/show/tgvbo9nq 本地图片转Base64(从而可以预览图片): function localImgLoad() { var src ...
随机推荐
- sql语句复制表
1.复制表结构及数据到新表CREATE TABLE 新表 SELECT * FROM 旧表 这种方法会将oldtable中所有的内容都拷贝过来,当然我们可以用delete from newtable; ...
- mac 自带 php 验证码 不显示
curl -s http://php-osx.liip.ch/install.sh | bash -s 5.5 在命令行中输入上面 ,最后5.5是php版本号 自动安装FreeType ----- ...
- apache rewrite .htaccess 站点内容重定向实例
<IfModule mod_rewrite.c> Options +FollowSymlinks RewriteEngine On RewriteCond %{REQUEST_FILENA ...
- 在Adobe Reader中保存PDF表单数据的方法
通常,Adobe Reader 用户填写表单后,是无法保存所填表单的副本的.但是,对于 Reader 8 和更高版本的用户,您可以扩展其权限,使他们可以完成此操作.如果您使用的是 Acrobat Pr ...
- 【C语言】结构组成(函数、语句、注释)
C语言结构组成 一.相关基础知识 二.具体内容 C语言由函数.语句和注释三部分组成: )函数与主函数: 一个C语言源程序可以由一个或多个源文件组成,每个源文件可由一个或多个函数组成,一个源程序 ...
- 粗谈CGI
先看看 维基百科上面关于 CGI的介绍http://zh.wikipedia.org/wiki/%E9%80%9A%E7%94%A8%E7%BD%91%E5%85%B3%E6%8E%A5%E5%8F% ...
- 最新game
#include <stdio.h> #include <stdlib.h> #include <string.h> #include <signal.h&g ...
- BZOJ 1018 堵塞的交通
Description 有一天,由于某种穿越现象作用,你来到了传说中的小人国.小人国的布局非常奇特,整个国家的交通系统可以被看成是一个2行C列的矩形网格,网格上的每个点代表一个城市,相邻的城市之间有一 ...
- Unity3d webplayer发布的问题和100%自适应浏览器
Unity3d发布的问题 发布的时候,遇到无法写入Resources.assets,原来是我的项目中有多个Resources文件夹,以后最好是不要有重复的文件夹和一样名字的资源! 还有就是发布的web ...
- 比较全面的gdb调试命令 (转载)
转自http://blog.csdn.net/dadalan/article/details/3758025 用GDB调试程序 GDB是一个强大的命令行调试工具.大家知道命令行的强大就是在于,其可以形 ...