Jersey实现文件上传下载
一 文件上传
使用ajaxFileUpload进行文件上传的前端处理。在ajaxFileupload.js中,针对服务端返回的类型增加text判断,
//ajax文件上传 function ajaxFileUpload(){ $.ajaxFileUpload({ type:"post", url: "../rest/api/file/upload", //用于文件上传的服务器端请求地址 secureuri: false, //是否需要安全协议,一般设置为false fileElementId: "file", //文件上传域的ID
dataType: "text", //返回值类型 一般设置为json
//contentType:"application/x-www-form-urlencoded;charset=UTF-8",
success: function (data) {//服务器成功响应处理函数
data = JSON.parse(data);
if (data.status == 'ok') { //进行execl解析,并返回数据更新进度条 var user_tagIds = $("#old_import_usertag_tagIds").val(); poiExecl(data.location, user_tagIds); // $('#progressModual').modal('show'); timer = setInterval("updateProgress()",'1000'); }else{ $('#progressPage').remove(); $('#uploadProgress').html("文件上传失败!"); } }, complete: function(xmlHttpRequest) { $("#file").on("change", filechange); }, error: function (data, status, e){ //服务器响应失败处理函数 } }); }
后端业务处理
返回的数据类型,指定媒体类型Mediatype为TEXT_PLAIN.
@POST @Path("/upload") @Consumes(MediaType.MULTIPART_FORM_DATA) @Produces(MediaType.TEXT_PLAIN) public Response uploadTemp( @FormDataParam("file") final InputStream uploadedInputStream, @FormDataParam("file") final FormDataContentDisposition fileDetail) { final String fileName = fileDetail.getFileName(); final String uploadedFileLocation = getClass().getResource( "/uploadtemp").getFile() + UUID.randomUUID() + fileName.substring(fileName.lastIndexOf("."), fileName.length()); FileUtil.writeToFile(uploadedInputStream, uploadedFileLocation); final JSONObject obj = new JSONObject(); obj.put("status", "ok"); obj.put("location", uploadedFileLocation); return Response.ok(obj, MediaType.APPLICATION_JSON).status(200) .entity(obj).build(); }
使用的媒体类型指定:MediaType.MULTIPART_FORM_DATA
二 文件下载
前端
$tempDownBtn.click(function() { var tempTypeDOM = document .getElementsByName("tempType"); var tempType = ""; for (var i = 0; i < tempTypeDOM.length; i++) { if (tempTypeDOM[i].checked) { tempType = tempTypeDOM[i].value; } } if ("" == tempType) { } else { location.href = "../rest/api/file/down?tempType=" + tempType; } });
后端
/** * 功能说明:模板下载 * @param servletContext context * @param request 请求 * @param response 响应 * @param tempType 模板类型 * @return <br/> * 修改历史:<br/> * 1.[2015年10月21日下午4:04:29] 创建方法 by hewu */ @GET @Path("/down") @Consumes({ MediaType.APPLICATION_FORM_URLENCODED, MediaType.APPLICATION_JSON }) public HttpServletResponse downTemp( @Context final ServletContext servletContext, @QueryParam("tempType") final String tempType) { String path = null; if (ExcelConstans.TEMP_TYPE_PERSON.equals(tempType)) { path = servletContext .getRealPath(ExcelConstans.ERR_PERSON_ACCOUNT_UPLOAD_DIR); } else if (ExcelConstans.TEMP_TYPE_ORGANIZE.equals(tempType)) { path = servletContext .getRealPath(ExcelConstans.ERR_ORGANIZE_ACCOUNT_UPLOAD_DIR); } else { return response; } final File file = new File(path); String filename = file.getName();
try {
//针对IE5~10 request.getHeader("User-Agent").toUpperCase().indexOf("MSIE")
//针对IE11 request.getHeader("User-Agent").indexOf("rv:11")
if (request.getHeader("User-Agent").toUpperCase().indexOf("MSIE") > 0
|| request.getHeader("User-Agent").indexOf("rv:11") > -1) {
filename = URLEncoder.encode(filename, "UTF-8");
} else {
filename = new String(filename.getBytes("UTF-8"), "ISO8859-1");
}
} catch (UnsupportedEncodingException e) { e.printStackTrace(); LOG.error("error to transition code", e); } InputStream fis = null; byte[] buffer = null; try { fis = new BufferedInputStream(new FileInputStream(path)); buffer = new byte[fis.available()]; fis.read(buffer); fis.close(); response.reset(); response.addHeader("Content-Disposition", "attachment;filename=" + filename); response.addHeader("Content-Length", "" + file.length()); final OutputStream toClient = new BufferedOutputStream( response.getOutputStream()); response.setContentType("application/vnd.ms-excel;charset=utf-8"); toClient.write(buffer); toClient.flush(); toClient.close(); } catch (FileNotFoundException e) { e.printStackTrace(); LOG.error("error to down load", e); } catch (IOException e) { e.printStackTrace(); LOG.error("error to down load", e); } return response; }
附录:
提供本人修改过的ajaxFileupload.js
jQuery.extend({ createUploadIframe: function(id, uri) { //create frame var frameId = 'jUploadFrame' + id; var ua=navigator.userAgent.toLowerCase(); if(window.ActiveXObject) { //ie 9~10 if ((ua.match(/msie/) != null) || (ua.match(/trident/) != null)) { var io = document.createElement('iframe'); io.id = frameId; io.name = frameId; //ie 6~8 } else if (!$.support.leadingWhitespace || 'undefined' == typeof(document.body.style.maxHeight)) { var io = document.createElement('<iframe id="' + frameId + '" name="' + frameId + '" />'); if (typeof uri == 'boolean') { io.src = 'javascript:false'; } else if (typeof uri == 'string') { io.src = uri; } } } else { var io = document.createElement('iframe'); io.id = frameId; io.name = frameId; } io.style.position = 'absolute'; io.style.top = '-1000px'; io.style.left = '-1000px'; document.body.appendChild(io); return io }, createUploadForm: function(id, fileElementId) { //create form var formId = 'jUploadForm' + id; var fileId = 'jUploadFile' + id; var form = $('<form action="" method="POST" name="' + formId + '" id="' + formId + '" enctype="multipart/form-data"></form>'); var oldElement = $('#' + fileElementId); var newElement = $(oldElement).clone(); $(oldElement).attr('id', fileId); $(oldElement).before(newElement); $(oldElement).appendTo(form); //set attributes $(form).css('position', 'absolute'); $(form).css('top', '-1200px'); $(form).css('left', '-1200px'); $(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 = s.fileElementId; var form = jQuery.createUploadForm(id, s.fileElementId); 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 { $(io).remove(); $(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 io = $('#' + frameId); var form = $('#' + formId); $(form).attr('action', s.url); $(form).attr('method', 'POST'); $(form).attr('target', frameId); if(form.encoding) { form.encoding = 'multipart/form-data'; } else { form.enctype = 'multipart/form-data'; } $(form).submit(); } catch(e) { jQuery.handleError(s, xml, null, e); } if(window.attachEvent){ document.getElementById(frameId).attachEvent('onload', uploadCallback); } else{ document.getElementById(frameId).addEventListener('load', uploadCallback, false); } 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" ) { ////////////以下为新增代码/////////////// 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); } if(type="text"){ data = $(data).text(); } // 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] ); } } })