本例使用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. 异步上传&预览图片-压缩图片

    移动端普及的时代,流量是用户最关心的,手机拍出来的照片基本上都在1~2M以上,这样上传会非常耗流量,影响用户体验,此例能在保证清晰度的情况下,将4.5M的图片压缩为30K <!DOCTYPE h ...

  2. 模拟QQ心情图片上传预览

    出于安全性能的考虑,目前js端不支持获取本地图片进行预览,正好在做一款类似于QQ心情的发布框,找了不少jquery插件,没几个能满足需求,因此自己使用SWFuplad来实现这个图片上传预览. 先粘上以 ...

  3. 用html5文件api实现移动端图片上传&预览效果

    想要用h5在移动端实现图片上传&预览效果,首先要了解html5的文件api相关知识(所有api只列举本功能所需): 1.Blob对象  Blob表示原始二进制数据,Html5的file对象就继 ...

  4. 微信开发中使用微信JSSDK和使用URL.createObjectURL上传预览图片的不同处理对比

    在做微信公众号或者企业微信开发业务应用的时候,我们常常会涉及到图片预览.上传等的处理,往往业务需求不止一张图片,因此相对来说,需要考虑的全面一些,用户还需要对图片进行预览和相应的处理,在开始的时候我使 ...

  5. 图片上传预览转压缩并转base64详解(dShowImg64.js)

    hello,大家好,游戏开始了,欢迎大家收看这一期的讲解.本次的内容是图片的上传预览.最后发源码链接.废话不多说,先上图. 待上传图像 点击蓝色框内,pc可以选择文件,移动端选择拍照或选择图片进行上传 ...

  6. FileReader()读取文件、图片上传预览

    前言 FileReader 对象允许Web应用程序异步读取存储在用户计算机上的文件(或原始数据缓冲区)的内容,使用 File 或 Blob 对象指定要读取的文件或数据. 其中File对象可以是来自用户 ...

  7. 兼容好的JS图片上传预览代码

    转 : http://www.codefans.net/articles/1395.shtml 兼容好的JS图片上传预览代码 (谷歌,IE11) <html xmlns="http:/ ...

  8. Jquery图片上传预览效果

    uploadPreview.js jQuery.fn.extend({ uploadPreview: function (opts) { var _self = this, _this = $(thi ...

  9. [前端 4] 使用Js实现图片上传预览

    导读:今天做图片上传预览,刚开始的做法是,先将图片上传到Nginx,然后重新加载页面才能看到这个图片.在这个过程中,用户一直都看不到自己上传的文件是什么样子.Ps:我发现我真的有强迫症了,都告诉我说不 ...

随机推荐

  1. 02 Python数据结构的性能分析

    一.列表: - python 的设计者在实现列表数据结构的时候有很多选择.每一个这种选择都可能影响列表操作的性能.为了帮助他们做出正确的选择,他们查看了最常使用列表数据结构的方式,并且优化了实现,以便 ...

  2. 上海的Costco,谈谈你的理解和感受

    众所周知,Costco在上海第一天开业,由于人流量过大,一度暂停营业.我觉得Costco的成功在于不走寻常路,换位思考(站在用户.厂商角度看问题),下面几点是我觉得它做得比较独特的地方: 1. Cos ...

  3. vue组件之属性Props

    组件的属性和事件 父子组件之间的通信 父子组件之间的通信就是 props down,events up,父组件通过 属性props向下传递数据给子组件,子组件通过 事件events 给父组件发送消息. ...

  4. python 模块使用

    模块使用 定义:模块就像一个工具包一样,里面有很多工具(函数.类),使用时需要通过import导入. 分类: 标准库:random.sys.os.time 第三方:就是好人已经写好的特定功能的模块,你 ...

  5. webpack4 打包

    1. 基本安装及命令 npm config set registry https://registry.npm.taobao.org     //  淘宝镜像npm install webpack-c ...

  6. magento购物车添加减少数量 实时更新购物车

    magento实时更新购物车商品数量 <td> <button onclick="addQtyone();" type="submit"> ...

  7. chown -R lyd usbsend

    chown -R lyd usbsend chown -R lyd usbsend chown -R lyd usbsend 某一个目录下所有文件授权给lyd

  8. 多对多第三张表的创建方式 和 forms组件的使用

    目录 一.多对多第三张表的创建 1. 全自动方式 (1)实现代码 (2)优点和不足 2. 纯手撸方式(了解) (1)实现代码 (2)优点和不足 3. 半自动方式(推荐使用) (1)实现代码 (2)优点 ...

  9. mysql数据库之表操作及字段约束条件

    目录 一.存储引擎 二.表介绍 三.创建表 四.查看表结构 五.数据类型 一.介绍 二.数值类型 整数类型 浮点型 三.字符串类型 四.日期类型 五.枚举类型与集合类型 六.约束条件 七.修改表 al ...

  10. HTML DOM 事件与方法

    HTML DOM 事件允许Javascript在HTML文档元素中注册不同事件处理程序. 事件通常与函数结合使用,函数不会在事件发生前被执行! (如用户点击按钮). 鼠标事件 键盘事件 框架/对象(F ...