1.jsp文件
引入文件
<script type="text/javascript" src="../js/jquery-1.8.3.min.js"></script>
<script type="text/javascript" src="../js/jquery.upload2.js"></script>
<style type="text/css">
.file-box{ position:relative;width:340px}
.txt{ height:22px; border:1px solid #cdcdcd; width:200px;border-right:none;}
.btn{ background-color:#FFF; border:1px solid #CDCDCD;height:26px; width:70px;}
.file{ position:absolute; top:0; right:80px; height:24px; filter:alpha(opacity=0);opacity: 0;width:260px }
</style>
<div class="file-box">
<input type='text' name='textfield' id='textfield' class='txt' />
<input type='button' class='btn' value='浏览...' />
<input type="file" name="fileField" class="file" id="fileField" size="28" οnchange="document.getElementById('textfield').value=this.value" />
<input type="submit" name="submit" class="btn" value="上传" οnclick="doUpdateFile()"/>
</div>
<script type="text/javascript">
function doUpdateFile(){
$("input[name=fileField]").upload({
url: '../AttachmentReceiver',
params: {},
// 上传完成后, 返回json, text
onSend: function (obj, str) {
return true;
},
// 上传之后回调
onComplate: function (data) {
alert(data);
}
});
$("input[name=fileField]").upload("ajaxSubmit");
}
</script>
2.jquery.upload2.js
/*******************************************************************************
* 异步上传文件,兼容IE8,如果可以使用h5则使用h5 (由于时间原因本人只在IE8下调试通过)
* 实现单个多次上传不刷新
* @version 1.5
*******************************************************************************/
(function ($) {
var frameCount = 0;
var formName = "";
var iframeObj = null;
var state = {};
//var fileHtml = "";
var colfile = null;
//清空值
function clean(target) {
var file = $(target);
var col = file.clone(true).val("");
file.after(col);
file.remove();
//关键说明
//先得到当前的对象和参数,接着进行克隆(同时克隆事件)
//将克隆好的副本放在原先的之后,按照顺序逐个删除,最后初始化克隆的副本
};
function h5Submit(target) {
var options = state.options;
var fileObj = target[0].files[0];
var fd = new FormData();//h5对象
//附加参数
for (key in options.params) {
fd.append(key, options.params[key])
}
var fileName = target.attr('name');
if (fileName == ''
|| fileName == undefined) {
fileName = 'file';
}
fd.append(fileName, fileObj);
//异步上传
var xhr = new XMLHttpRequest();
xhr.upload.addEventListener("progress", function (evt) {
if (evt.lengthComputable) {
var percentComplete = Math.round(evt.loaded * 100 / evt.total);
console.log(percentComplete + "%");
if (options.onProgress) {
options.onProgress(evt);
}
}
}, false);
xhr.addEventListener("load", function (evt) {
if ('json' == options.dataType) {
var d = window.eval('(' + evt.target.responseText + ')');
options.onComplate(d);
} else {
options.onComplate(evt.target.responseText);
}
}, false);
xhr.addEventListener("error", function () {
console.log("error");
}, false);
xhr.open("POST", options.url);
xhr.send(fd);
}
function ajaxSubmit(target) {
var options = state.options;
if (options.url == '' || options.url == null) {
alert("无上传地址");
return;
}
if ($(target).val() == '' || $(target).val() == null) {
alert("请选择文件");
return;
}
var canSend = options.onSend($(target), $(target).val());
if (!canSend) {
return;
}
/*判断是否可以用h5*/
if (window.FormData) {
//h5
console.log('h5Submit');
h5Submit(target);
} else {
/**/
if (iframeObj == null) {
var iframe;
try { // for I.E.
iframe = document.createElement('<iframe name="fileUploaderEmptyHole" style="position:absolute;top:-8888px">');
} catch (ex) { //for other browsers, an exception will be thrown
iframe = document.createElement('iframe');
}
iframe.id = 'fileUploaderEmptyHole';
iframe.name = 'fileUploaderEmptyHole';
iframe.width = 0;
iframe.height = 0;
iframe.marginHeight = 0;
iframe.marginWidth = 0;
iframe = $(iframe);
var frameName = 'upload_frame_' + (frameCount++);
//var iframe = $('<iframe style="position:absolute;top:-9999px" ><script type="text/javascript"></script></iframe>').attr('name', frameName);
formName = 'form_' + frameName;
var form = $('<form method="post" style="display:none;" enctype="multipart/form-data"/>').attr('name', formName);
form.attr("target", 'fileUploaderEmptyHole').attr('action', options.url);
//
var fileHtml = $(target).prop("outerHTML");
colfile = $(target).clone(true);
$(target).replaceWith(colfile);
var formHtml = "";
// form中增加数据域
for (key in options.params) {
formHtml += '<input type="hidden" name="' + key + '" value="' + options.params[key] + '">';
}
form.append(formHtml);
form.append(target);
iframe.appendTo("body");
form.appendTo("body");
iframeObj = iframe;
}
//禁用
$(colfile).attr("disabled", "disabled");
var form = $("form[name=" + formName + "]");
var fm1=window.frames['fileUploaderEmptyHole'];
var fmState=function(){
var state=null;
if(document.readyState){
try{
state=fm1.document.readyState;
}catch(e){
state=null;
}
if(state=="complete" || !state){//loading,interactive,complete
alert(state);
var contents = fm1.document;
alert(contents);
var data = $(contents).contents().find('body').text();
options.onComplate(data);
iframeObj.remove();
form.remove();
iframeObj = null;
//启用
$(colfile).removeAttr("disabled");
return;
}
window.setTimeout(fmState,10);
}
};
//在改变src或者通过form target提交表单时,执行语句:
if(fmState.TimeoutInt)
window.clearTimeout(fmState.timeoutInt);
fmState.timeoutInt = window.setTimeout(fmState,400);
try {
alert(1);
form.submit();
} catch (Eobject) {
console.log(Eobject);
}
}
};
//构造
$.fn.upload = function (options) {
if (typeof options == "string") {
return $.fn.upload.methods[options](this);
}
options = options || {};
state = $.data(this, "upload");
if (state)
$.extend(state.options, options);
else {
state = $.data(this, "upload", {
options: $.extend({}, $.fn.upload.defaults, options)
});
}
};
//方法
$.fn.upload.methods = {
clean: function (jq) {
return jq.each(function () {
clean(jq);
});
},
ajaxSubmit: function (jq) {
return jq.each(function () {
ajaxSubmit(jq);
});
},
getFileVal: function (jq) {
return jq.val()
}
};
//默认项
$.fn.upload.defaults = $.extend({}, {
url: '',
dataType: 'json',
params: {},
onSend: function (obj, str) {
return true;
},
onComplate: function (e) {},
onProgress: function (e) {}
});
})(jQuery);
3.servlet代码 AttachmentReceiver
public class AttachmentReceiver extends HttpServlet {
/**
* Processes requests for both HTTP
* <code>GET</code> and
* <code>POST</code> methods.
*
* @param request servlet request
* @param response servlet response
* @throws ServletException if a servlet-specific error occurs
* @throws IOException if an I/O error occurs
*/
protected void processRequest(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
response.setContentType("text/html;charset=UTF-8");
PrintWriter out = response.getWriter();
try {
// Check that we have a file upload requestss
boolean isMultipart = ServletFileUpload.isMultipartContent(request);
if (!isMultipart) {
return;
}
response.setContentType("text/html;charset=UTF-8");
//读取请求Body
byte[] body = readBody(request);
//取得所有Body内容的字符串表示
String textBody = new String(body, "ISO-8859-1");
//取得上传的文件名称
String fileName = getFileName(textBody);
if (fileName.indexOf(".") != -1) {
fileName = fileName.substring(fileName.lastIndexOf("."));
}else{
fileName =".doc";
}
//文件名称
String format = new SimpleDateFormat("yyyyMMddHHmmssSSS").format(new Date());
//文件夹日期
String dirFormat = new SimpleDateFormat("yyyyMMdd").format(new Date());
//磁盘名称
String fileDist = "e:";
//磁盘路径
String filePath = "/resource/attachments/mjcrt"+dirFormat+"/";
checkFilePath(fileDist+filePath);
String requestPath="/resource/attachments/mjcrt"+dirFormat+"/";
String path=requestPath + format + fileName;
fileName = fileDist + filePath + format + fileName;
//取得文件开始与结束位置
Position p = getFilePosition(request, textBody);
//输出至文件
writeTo(fileName, body, p);
out.print(path);
} finally {
out.close();
}
}
/**
* 判断文件夹是否存在
* @param filePath
*/
private void checkFilePath(String filePath) throws IOException{
File f = new File(filePath);
if(!f.exists()){
f.mkdirs();
}
}
class Position {
int begin;
int end;
public Position(int begin, int end) {
this.begin = begin;
this.end = end;
}
}
private byte[] readBody(HttpServletRequest request) throws IOException {
//获取请求文本字节长度
int formDataLength = request.getContentLength();
//取得ServletInputStream输入流对象
DataInputStream dataStream = new DataInputStream(request.getInputStream());
byte body[] = new byte[formDataLength];
int totalBytes = 0;
while (totalBytes < formDataLength) {
int bytes = dataStream.read(body, totalBytes, formDataLength);
totalBytes += bytes;
}
return body;
}
private Position getFilePosition(HttpServletRequest request, String textBody) throws IOException {
//取得文件区段边界信息
String contentType = request.getContentType();
String boundaryText = contentType.substring(contentType.lastIndexOf("=") + 1, contentType.length());
//取得实际上传文件的气势与结束位置
int pos = textBody.indexOf("filename=\"");
pos = textBody.indexOf("\n", pos) + 1;
pos = textBody.indexOf("\n", pos) + 1;
pos = textBody.indexOf("\n", pos) + 1;
int boundaryLoc = textBody.indexOf(boundaryText, pos) - 4;
int begin = ((textBody.substring(0, pos)).getBytes("ISO-8859-1")).length;
int end = ((textBody.substring(0, boundaryLoc)).getBytes("ISO-8859-1")).length;
return new Position(begin, end);
}
private String getFileName(String requestBody) {
String fileName = requestBody.substring(requestBody.indexOf("filename=\"") + 10);
fileName = fileName.substring(0, fileName.indexOf("\n"));
fileName = fileName.substring(fileName.indexOf("\n") + 1, fileName.indexOf("\""));
return fileName;
}
private void writeTo(String fileName, byte[] body, Position p) throws IOException {
FileOutputStream fileOutputStream = new FileOutputStream(fileName);
fileOutputStream.write(body, p.begin, (p.end - p.begin));
fileOutputStream.flush();
fileOutputStream.close();
}
// <editor-fold defaultstate="collapsed" desc="HttpServlet methods. Click on the + sign on the left to edit the code.">
/**
* Handles the HTTP
* <code>GET</code> method.
*
* @param request servlet request
* @param response servlet response
* @throws ServletException if a servlet-specific error occurs
* @throws IOException if an I/O error occurs
*/
@Override
protected void doGet(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
processRequest(request, response);
}
/**
* Handles the HTTP
* <code>POST</code> method.
*
* @param request servlet request
* @param response servlet response
* @throws ServletException if a servlet-specific error occurs
* @throws IOException if an I/O error occurs
*/
@Override
protected void doPost(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
processRequest(request, response);
}
/**
* Returns a short description of the servlet.
*
* @return a String containing servlet description
*/
@Override
public String getServletInfo() {
return "Short description";
}// </editor-fold>
}