异步上传&预览图片-不压缩图片
本例使用ajaxFileUpload异步上传预览图片
<bean id="multipartResolver" class="org.springframework.web.multipart.commons.CommonsMultipartResolver">
<property name="maxUploadSize">
<value>10485760000</value>
</property>
<property name="maxInMemorySize">
<value>4096</value>
</property>
</bean>
springmvc.xml
<!DOCTYPE html>
<html>
<head>
<title>HTML5上传图片预览</title>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
<script src="http://www.codefans.net/ajaxjs/jquery-1.6.2.min.js"></script>
<script src="./ajaxfileupload.js"></script>
</head>
<body>
<h3>请选择图片文件:JPG/GIF</h3> <input type="button" onclick="uploadImages('file0')" value="上传"/>
<form name="form0" id="form0" >
<input type="file" name="file0" id="file0" multiple="multiple" /><br><img src="" id="img0" > </form>
<script>
$("#file0").change(function(){
var objUrl = getObjectURL(this.files[0]) ;
if (objUrl) {
$("#img0").attr("src", objUrl) ;
}
}) ;
//建立一個可存取到該file的url
function getObjectURL(file) {
var url = null ;
if (window.createObjectURL!=undefined) { // basic
url = window.createObjectURL(file) ;
} else if (window.URL!=undefined) { // mozilla(firefox)
url = window.URL.createObjectURL(file) ;
} else if (window.webkitURL!=undefined) { // webkit or chrome
url = window.webkitURL.createObjectURL(file) ;
}
return url ;
}
function uploadImages(type) {
ajax_upload(type,type,function(data) { //function(data)是上传图片的成功后的回调方法
var isrc = data.relatPath.replace(/\/\//g, '/'); //获取的图片的绝对路径
console.log(isrc) //给<input>的src赋值去显示图片
});
} function ajax_upload(type,feid, callback) { //具体的上传图片方法
if (image_check(feid)) { //自己添加的文件后缀名的验证
$.ajaxFileUpload({
fileElementId: feid, //需要上传的文件域的ID,即<input type="file">的ID。
url: 'http://****/upload.htm?updateP='+type, //后台方法的路径
type: 'post', //当要提交自定义参数时,这个参数要设置成post
dataType: 'json', //服务器返回的数据类型。可以为xml,script,json,html。如果不填写,jQuery会自动判断。
secureuri: false, //是否启用安全提交,默认为false。
async : true, //是否是异步
success: function(data) { //提交成功后自动执行的处理函数,参数data就是服务器返回的数据。
if (callback) callback.call(this, data);
},
error: function(data, status, e) { //提交失败自动执行的处理函数。
console.error(e);
}
});
}
}
function image_check(feid) { //自己添加的文件后缀名的验证
var img = document.getElementById(feid);
return /.(jpg|png|gif|bmp)$/.test(img.value)?true:(function() {
modals.info('图片格式仅支持jpg、png、gif、bmp格式,且区分大小写。');
return false;
})();
}
</script>
</body>
</html>
up.html
jQuery.extend({ createUploadIframe: function(id, uri)
{
//create frame
var frameId = 'jUploadFrame' + id;
var iframeHtml = '<iframe id="' + frameId + '" name="' + frameId + '" style="position:absolute; top:-9999px; left:-9999px"';
if(window.ActiveXObject)
{
if(typeof uri== 'boolean'){
iframeHtml += ' src="' + 'javascript:false' + '"'; }
else if(typeof uri== 'string'){
iframeHtml += ' src="' + uri + '"'; }
}
iframeHtml += ' />';
jQuery(iframeHtml).appendTo(document.body); return jQuery('#' + frameId).get(0);
},
createUploadForm: function(id, fileElementId, data)
{
//create form
var formId = 'jUploadForm' + id;
var fileId = 'jUploadFile' + id;
var form = jQuery('<form action="" method="POST" name="' + formId + '" id="' + formId + '" enctype="multipart/form-data"></form>');
if(data)
{
for(var i in data)
{
jQuery('<input type="hidden" name="' + i + '" value="' + data[i] + '" />').appendTo(form);
}
}
var oldElement = jQuery('#' + fileElementId);
var newElement = jQuery(oldElement).clone();
jQuery(oldElement).attr('id', fileId);
jQuery(oldElement).before(newElement);
jQuery(oldElement).appendTo(form); //set attributes
jQuery(form).css('position', 'absolute');
jQuery(form).css('top', '-1200px');
jQuery(form).css('left', '-1200px');
jQuery(form).appendTo('body');
return form;
}, ajaxFileUpload: function(s) {
// TODO introduce global settings, allowing the client to modify them for all requests, not only timeout
s = jQuery.extend({}, jQuery.ajaxSettings, s);
var id = new Date().getTime()
var form = jQuery.createUploadForm(id, s.fileElementId, (typeof(s.data)=='undefined'?false:s.data));
var io = jQuery.createUploadIframe(id, s.secureuri);
var frameId = 'jUploadFrame' + id;
var formId = 'jUploadForm' + id;
// Watch for a new set of requests
if ( s.global && ! jQuery.active++ )
{
jQuery.event.trigger( "ajaxStart" );
}
var requestDone = false;
// Create the request object
var xml = {}
if ( s.global )
jQuery.event.trigger("ajaxSend", [xml, s]);
// Wait for a response to come back
var uploadCallback = function(isTimeout)
{
var io = document.getElementById(frameId);
try
{
if(io.contentWindow)
{
xml.responseText = io.contentWindow.document.body?io.contentWindow.document.body.innerHTML:null;
xml.responseXML = io.contentWindow.document.XMLDocument?io.contentWindow.document.XMLDocument:io.contentWindow.document; }else if(io.contentDocument)
{
xml.responseText = io.contentDocument.document.body?io.contentDocument.document.body.innerHTML:null;
xml.responseXML = io.contentDocument.document.XMLDocument?io.contentDocument.document.XMLDocument:io.contentDocument.document;
}
}catch(e)
{
jQuery.handleError(s, xml, null, e);
}
if ( xml || isTimeout == "timeout")
{
requestDone = true;
var status;
try {
status = isTimeout != "timeout" ? "success" : "error";
// Make sure that the request was successful or notmodified
if ( status != "error" )
{
// process the data (runs the xml through httpData regardless of callback)
var data = jQuery.uploadHttpData( xml, s.dataType );
// If a local callback was specified, fire it and pass it the data if ( s.success ) {
s.success( data, status );
} // Fire the global callback
if( s.global )
jQuery.event.trigger( "ajaxSuccess", [xml, s] );
} else
jQuery.handleError(s, xml, status);
} catch(e)
{
status = "error";
jQuery.handleError(s, xml, status, e);
} // The request was completed
if( s.global )
jQuery.event.trigger( "ajaxComplete", [xml, s] ); // Handle the global AJAX counter
if ( s.global && ! --jQuery.active )
jQuery.event.trigger( "ajaxStop" ); // Process result
if ( s.complete )
s.complete(xml, status); jQuery(io).unbind() setTimeout(function()
{ try
{
jQuery(io).remove();
jQuery(form).remove(); } catch(e)
{
jQuery.handleError(s, xml, null, e);
} }, 100) xml = null }
}
// Timeout checker
if ( s.timeout > 0 )
{
setTimeout(function(){
// Check to see if the request is still happening
if( !requestDone ) uploadCallback( "timeout" );
}, s.timeout);
}
try
{ var form = jQuery('#' + formId);
jQuery(form).attr('action', s.url);
jQuery(form).attr('method', 'POST');
jQuery(form).attr('target', frameId);
if(form.encoding)
{
jQuery(form).attr('encoding', 'multipart/form-data');
}
else
{
jQuery(form).attr('enctype', 'multipart/form-data');
}
jQuery(form).submit(); } catch(e)
{
jQuery.handleError(s, xml, null, e);
} jQuery('#' + frameId).load(uploadCallback );
return {abort: function () {}}; }, uploadHttpData: function( r, type ) {
var data = !type;
data = type == "xml" || data ? r.responseXML : r.responseText;
// If the type is "script", eval it in global context
if ( type == "script" )
jQuery.globalEval( data );
// Get the JavaScript object, if JSON is used.
if ( type == "json" ) {
//chrome含style,firefox不含
data = r.responseText;
var start = data.indexOf(">");
if(start != -1) {
var end = data.indexOf("<", start + 1);
if(end != -1) {
data = data.substring(start + 1, end);
}
}
eval( "data = " + data );
}
// evaluate scripts within html
if ( type == "html" )
jQuery("<div>").html(data).evalScripts(); return data;
},
handleError: function( s, xhr, status, e ){
// If a local callback was specified, fire it
if ( s.error ) {
s.error.call( s.context || s, xhr, status, e );
} // Fire the global callback
if ( s.global ) {
(s.context ? jQuery(s.context) : jQuery.event).trigger( "ajaxError", [xhr, s, e] );
}
}
})
ajaxfileupload.js
public void upload(HttpServletRequest request,HttpServletResponse response) throws Exception {
String type=request.getParameter("updateP");
MultipartHttpServletRequest multipartRequest = (MultipartHttpServletRequest) request;
CommonsMultipartFile file = (CommonsMultipartFile) multipartRequest.getFile(type); String rootDir = request.getRealPath("/");
String relatDir = File.separator+"uploadimg";
//文件夹不存在则创建
File fdir = new File(rootDir+relatDir);
if (!fdir.exists()) {
fdir.mkdirs();
} String oriName = file.getOriginalFilename();
String newName = new Date().getTime()+"_"+oriName;
File tempFile = new File(fdir.getPath()+File.separator+newName);
file.transferTo(tempFile); Map<String, String> result = new HashMap();
result.put("oriName", oriName);
result.put("realName", tempFile.getName());
result.put("relatPath", relatDir+File.separator+newName);
sendjson(result, response);
//return null;
}
/**
* 发送json
* @param pmap 封装数据
* @param response
*/
public void sendjson(Map pmap,HttpServletResponse response){
String output = JSONObject.toJSONString(pmap);
try {
response.setContentType("text/html");
response.setCharacterEncoding("UTF-8");
response.getWriter().print(output);
} catch (IOException e) {
e.printStackTrace();
}
} /**
*
* @param stream 上传文件流
* @param path 保存路径
* @param filename 文件名称
* @throws IOException
*/
public void SaveFileFromInputStream(InputStream stream,String path,String filename) throws IOException{
FileOutputStream fs=new FileOutputStream( path + "/"+ filename);
byte[] buffer =new byte[1024*1024];
int bytesum = 0;
int byteread = 0;
while ((byteread=stream.read(buffer))!=-1){
bytesum+=byteread;
fs.write(buffer,0,byteread);
fs.flush();
}
fs.close();
stream.close();
}
javaCode
异步上传&预览图片-不压缩图片的更多相关文章
- 异步上传&预览图片-压缩图片
移动端普及的时代,流量是用户最关心的,手机拍出来的照片基本上都在1~2M以上,这样上传会非常耗流量,影响用户体验,此例能在保证清晰度的情况下,将4.5M的图片压缩为30K <!DOCTYPE h ...
- 模拟QQ心情图片上传预览
出于安全性能的考虑,目前js端不支持获取本地图片进行预览,正好在做一款类似于QQ心情的发布框,找了不少jquery插件,没几个能满足需求,因此自己使用SWFuplad来实现这个图片上传预览. 先粘上以 ...
- 用html5文件api实现移动端图片上传&预览效果
想要用h5在移动端实现图片上传&预览效果,首先要了解html5的文件api相关知识(所有api只列举本功能所需): 1.Blob对象 Blob表示原始二进制数据,Html5的file对象就继 ...
- 微信开发中使用微信JSSDK和使用URL.createObjectURL上传预览图片的不同处理对比
在做微信公众号或者企业微信开发业务应用的时候,我们常常会涉及到图片预览.上传等的处理,往往业务需求不止一张图片,因此相对来说,需要考虑的全面一些,用户还需要对图片进行预览和相应的处理,在开始的时候我使 ...
- 图片上传预览转压缩并转base64详解(dShowImg64.js)
hello,大家好,游戏开始了,欢迎大家收看这一期的讲解.本次的内容是图片的上传预览.最后发源码链接.废话不多说,先上图. 待上传图像 点击蓝色框内,pc可以选择文件,移动端选择拍照或选择图片进行上传 ...
- FileReader()读取文件、图片上传预览
前言 FileReader 对象允许Web应用程序异步读取存储在用户计算机上的文件(或原始数据缓冲区)的内容,使用 File 或 Blob 对象指定要读取的文件或数据. 其中File对象可以是来自用户 ...
- 兼容好的JS图片上传预览代码
转 : http://www.codefans.net/articles/1395.shtml 兼容好的JS图片上传预览代码 (谷歌,IE11) <html xmlns="http:/ ...
- Jquery图片上传预览效果
uploadPreview.js jQuery.fn.extend({ uploadPreview: function (opts) { var _self = this, _this = $(thi ...
- [前端 4] 使用Js实现图片上传预览
导读:今天做图片上传预览,刚开始的做法是,先将图片上传到Nginx,然后重新加载页面才能看到这个图片.在这个过程中,用户一直都看不到自己上传的文件是什么样子.Ps:我发现我真的有强迫症了,都告诉我说不 ...
随机推荐
- wex5 file文件存储
在js中需要引入file的cordova包 require("cordova!cordova-plugin-file"); 如果要存到手机的根目录下,在Native文件夹的对应项目 ...
- Vue-cli脚手架起步
1.安装node.js 下载地址:http://nodejs.cn/download/ 测试是否安装成功 node -V 检测安装包 npm -v 检测npm 2.安装webpack npm inst ...
- java基础2(Map)
1.请简述Map 的特点 Map每个元素由键与值两部分组成 Map键不能重复,每个键对应一个值 键和值可以为null 2.说出Entry键值对对象遍历Map集合的原理. Map中存放的是两种对象,一种 ...
- 测试用例管理工具-TestLink
TestLink是基于web的测试用例管理系统,主要功能是测试用例的创建.管理和执行,并且还提供了一些简单的统计功能,主要功能包括: 测试需求管理 测试用例管理 测试用例对测试需求的覆盖管理 测试计划 ...
- 两种解决springboot 跨域问题的方法示例
两种解决springboot 跨域问题的方法示例,哪种方法看情况而定,自己选择.社会Boolean哥,人狠话不多,直接上代码. 第一种实现方式: 此种方式做全局配置,用起来更方便,但是无法 ...
- 第一篇、Python入门
一 编程与编程语言 python是一门编程语言,作为学习python的开始,需要事先搞明白:编程的目的是什么?什么是编程语言?什么是编程? 编程的目的: #计算机的发明,是为了用机器取代/解放人力,而 ...
- 2019.9.27PHP基础
PHP 基础语法规范: 1 <?php 开头 ?>结尾 2 php可以单独存在也可以和html等结合使用 3后缀名一般以.php结尾 php4,php5,php6,php7,phtml. ...
- linux 网卡配置详情
1.配置文件/etc/hosts(本地主机ip地址映射,可以有多个别名)./etc/services(端口号与标准服务之间的对应关系)./etc/sysconfig/network(设置主机名,网关, ...
- php和redis实现消息队列
php+redis消息队列是php+mysql性能不足时的一个中间间处理方案.通过这个中间的处理,保证的数据的可用性和准确性.用于服务器瞬间请求大,数据库压力大的情况.如并发量大导致的超卖.并发量大导 ...
- 使用putty对linux与windows之间的文件传输
一.putty下载 首先下载pytty,解压开发现里面有plink.exe pscp.exe psftp.exe putty.exe puttygen.exe puttytel.exe等可执行文件 进 ...