您的位置:首页 > Web前端 > JQuery

Java 夹杂文本字段的文件上传 后台实现(包括前端jquery实现的备忘)

2016-01-04 17:50 609 查看
简述:

使用了FileItem,对网页端 带有字段的Input文本 ,所以会有nameValuePair这个map的存在

以及文件上传做处理,

知识点

1. 后台文件夹杂表单字段上传的解析,以及文件的本地保存

2. 前端JS一些常用函数,包括url解析,获取contextPath, 简单的正则解析带一层标签的文本(用于解析<pre..>JSON Str</pre>格式)

3. jquery选择器的简单试用

后台实现主要代码:

[java] view
plaincopy

/**

* 文件上传表单处理,保存文件的路径, 同时记录表单内的值对

* @param request

* @param childPath 项目部署到服务器,存储的子路径

* @param nameValuePair 存放名字值对

* @return

*/

protected String saveUploadFile(HttpServletRequest request, final String childPath,

Map<String, String> nameValuePair){

//文件在服务器保存的路径

String path = null;

//外部访问路径

String fileSuffix = null;

String fileName = null;

//判断提交过来的表单是否为文件上传菜单

boolean isMultipart= ServletFileUpload.isMultipartContent(request);

if(isMultipart){

//构造一个文件上传处理对象

FileItemFactory factory = new DiskFileItemFactory();

ServletFileUpload upload = new ServletFileUpload(factory);

Iterator items;

try{

//解析表单中提交的所有文件内容

items = upload.parseRequest(request).iterator();

while(items.hasNext()){

FileItem item = (FileItem) items.next();

if(!item.isFormField()){

//取出上传文件的文件名称

String name = item.getName();

//取得上传文件以后的存储路径

fileSuffix = name.substring(name.lastIndexOf('.'), name.length());

//时间到微秒取 文件名

SimpleDateFormat sdf = new SimpleDateFormat("yyyyMMdd_HHmmssSSS");

fileName = sdf.format(new Date());

//上传文件以后的存储路径

String saveDir = this.getServletContext().getRealPath(childPath);

if (!(new File(saveDir).isDirectory())){

new File(saveDir).mkdir();

}

path = saveDir + File.separatorChar + fileName + fileSuffix;

//上传文件

File uploaderFile = new File(path);

item.write(uploaderFile);

}else{

String name = item.getFieldName();

String value = item.getString( "UTF-8");

nameValuePair.put(name, value);

logger.info("name: " + name +"\nvalue: " + value );

}

}

}catch(Exception e){

e.printStackTrace();

return null;

}

}

//返回客户端访问的地址

String requestUrl = nameValuePair.get("contextPath") + childPath + fileName + fileSuffix;

return requestUrl;

}

前端Javascript代码部分,现只在chrome上调试,firefox上传的回调函数success还是有问题:

在编程过程中发现试用ajaxFileUpload.js文件上传库在返回的时候自带<pre。。> 标签,所以filetype: text, 对返回的文本在转JSON后显示

[html] view
plaincopy

<script type="text/javascript">

function GetContextPath(){

var localObj = window.location;

var contextPath = localObj.pathname.split("/")[1];

var basePath = localObj.protocol+"//"+localObj.host+"/"+contextPath;

return basePath;

}

//获取URL中参数

function GetRequest() {

var url = location.search; //获取url中"?"符后的字串

var theRequest = new Object();

if (url.indexOf("?") != -1) {

var str = url.substr(1);

strs = str.split("&");

for(var i = 0; i < strs.length; i ++) {

theRequest[strs[i].split("=")[0]]=unescape(strs[i].split("=")[1]);

}

}

return theRequest;

}

function ParseTextToJsonObject(data){

var reg = /<pre.+?>(.*)<\/pre>/g;

data.match(reg);

var jsonStr = RegExp.$1;

if(jsonStr != "")

obj = jQuery.parseJSON(jsonStr);

else

obj =jQuery.pareseJSON(data);

return obj;

}

function ajaxFileUploadUnitImage() {

$.ajaxFileUpload({

url : "./building?action=UploadUnitImage" , //submit to UploadFileServlet

data: {

contextPath: GetContextPath(),

unitId: $("#unitId").val(),

imageType: $("#imageTypeSelector").val(),

label: $("#labelInput").val(),

userDescribe: $("#userDescribeInput").val()

},

secureuri : false,

fileElementId : 'fileToUpload',

dataType : 'text',

success : function(data, status) {

//转换为JSON对象

var obj = ParseTextToJsonObject(data);

UpdateColumn(obj);

},

error : function(data, status, e) {

console.info("Error");

alert("上传文件为空");

}

});

return false;

}

function DeleteUnitImage(unitImageId){

jQuery.ajax({

type:"GET",

url: "./building?action=DeleteUnitImage"

+ "&unitId=" + $('input[name="unitId"]').attr('value')

+ "&unitImageId=" + unitImageId,

dataType:"json",

global:false,

success: function(data){

UpdateColumn(data);

},

error: function(data){

alert("删除失败");

}

});

}

</script>

</head>

<body>

<h3 class="left">图片上传</h3>

</div>

<!-- upload file -->

<form name="form" method="POST" enctype="multipart/form-data">

<table class="tableForm">

<tbody>

<tr>

<td>

<input type="text" name="unitId" value=""><br/>

</td>

</tr>

<tr>

<select id="imageTypeSelector" name="imageType" >

<option value="0" selected="selected">户型图</option>

<option value="1">图2</option>

<option value="2">图3</option>

</select>

</tr>

<tr>

<td>

<label class="">二级标签: </label>

</td>

<td>

<input id="labelInput" type="text" name="label" >

</td>

</tr>

<tr>

<td>

<label class="">用户描述: </label>

</td>

<td>

<input id="userDescribeInput" type="text" name="userDescribe" >

</td>

</tr>

<tr>

<td><input id="fileToUpload" type="file" size="45"

name="fileToUpload" class="input"></td>

</tr>

</tbody>

<tfoot>

<tr>

<td><button class="button" id="buttonUpload"

onclick="return ajaxFileUploadUnitImage();">Upload</button></td>

</tr>

</tfoot>

</table>

</form>

</body>

</html>

后面是试用的AjaxFileUpload.js库,jquery用的是1.8.3

ajaxfileupload.js 需要添加handleError函数,这个函数存在于早起jquery版本,但是ajaxfileupload库还是沿用了,所以要人为地加入

[javascript] view
plaincopy

jQuery.extend({

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] );

}

},

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" )

eval( "data = " + data );

// evaluate scripts within html

if ( type == "html" )

jQuery("<div>").html(data).evalScripts();

return data;

}

})

界面简图:

内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: