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] );
}
}
})
Jersey实现文件上传下载的更多相关文章
- Struts的文件上传下载
Struts的文件上传下载 1.文件上传 Struts2的文件上传也是使用fileUpload的组件,这个组默认是集合在框架里面的.且是使用拦截器:<interceptor name=" ...
- Android okHttp网络请求之文件上传下载
前言: 前面介绍了基于okHttp的get.post基本使用(http://www.cnblogs.com/whoislcj/p/5526431.html),今天来实现一下基于okHttp的文件上传. ...
- Selenium2学习-039-WebUI自动化实战实例-文件上传下载
通常在 WebUI 自动化测试过程中必然会涉及到文件上传的自动化测试需求,而开发在进行相应的技术实现是不同的,粗略可划分为两类:input标签类(类型为file)和非input标签类(例如:div.a ...
- 艺萌文件上传下载及自动更新系统(基于networkComms开源TCP通信框架)
1.艺萌文件上传下载及自动更新系统,基于Winform技术,采用CS架构,开发工具为vs2010,.net2.0版本(可以很容易升级为3.5和4.0版本)开发语言c#. 本系统主要帮助客户学习基于TC ...
- 艺萌TCP文件上传下载及自动更新系统介绍(TCP文件传输)(一)
艺萌TCP文件上传下载及自动更新系统介绍(TCP文件传输) 该系统基于开源的networkComms通讯框架,此通讯框架以前是收费的,目前已经免费并开元,作者是英国的,开发时间5年多,框架很稳定. 项 ...
- ssh框架文件上传下载
<!doctype html> <html lang="en"> <head> <meta charset="UTF-8&quo ...
- SpringMVC——返回JSON数据&&文件上传下载
--------------------------------------------返回JSON数据------------------------------------------------ ...
- 【FTP】FTP文件上传下载-支持断点续传
Jar包:apache的commons-net包: 支持断点续传 支持进度监控(有时出不来,搞不清原因) 相关知识点 编码格式: UTF-8等; 文件类型: 包括[BINARY_FILE_TYPE(常 ...
- NetworkComms 文件上传下载和客户端自动升级(非开源)
演示程序下载地址:http://pan.baidu.com/s/1geVfmcr 淘宝地址:https://shop183793329.taobao.com 联系QQ号:3201175853 许可:购 ...
随机推荐
- mysql 远程登录与表名大小写问题
好久没写博客了,这段时间在学习一个开源的项目,里面使用到了mysql,好久没使用mysql了.在使用过程中遇到了一个问题,远程登陆.报错信息很明显,连接失败.解决思路如下: 1. 首先检查到服务器网络 ...
- charles 抓取app端 https 请求
测试需要抓取app的https请求链接,百度了一下教程,能设置的都设置成功了,但就是抓取不成功,显示如下图 无奈之下还是用谷歌搜索了下(网速极慢),但是庆幸的找到了问题的答案,原因还是手机设置的问 打 ...
- Go:创建新进程(os.StartProcess源码解读)
关于如何使用go语言实现新进程的创建和进程间通信,我在网上找了不少的资料,但是始终未能发现让自己满意的答案,因此我打算自己来分析这部分源代码,然后善加利用,并且分享给大家,期望大家能从中获得启发. 首 ...
- Windows10远程报错:由于CredSSP加密Oracle修正(ps:Win10家庭版)
Windows10远程桌面连接 报错信息 : 网上找到方法 但是奈何是 "Win10家庭版" 不能使用这个办法,具体操作可以看最后的引用链接 !!!! 策略路径:“计算机配置”-& ...
- spoj Longest Common Substring
Longest Common Substring SPOJ - LCS 题意:求两个串的最长公共子串 /* 对一个串建立后缀自动机,用另一个串上去匹配 */ #include<iostream& ...
- COM编程快速入门
COM编程快速入门 COM编程快速入门 http://www.vckbase.com/index.php/wv/1642 COM是一种跨应用和语言共享二进制代码的方法.与C++不同,它提倡源代码重 ...
- Photoshop在网页设计中的应用与方法
1.图像局部截取和图像尺寸调整 做网页设计时经常要用到的某张图像一部分,这就需要截取图像的局部.图像局部截取的方法很多,但使用Photoshop操作起来更方便.具体操作步骤如下: (1)在Photos ...
- hdu2067 小兔的棋盘
小兔的棋盘 时间限制:1000/1000 MS(Java / Others)内存限制:32768/32768 K(Java / Others)总提交内容:13029接受的提交内容:6517 问题描述 ...
- pandas学习2(基础操作)
- 压测工具 ab jmeter
apach ab|abs ab -n -c xxx.html/js/css jmeter siege 用途:测试分布式锁是否有效, 测试java Lock是否使用正确,测试接口吞吐量