文件上传、下载

//jsp页面代码
<%@ page contentType="text/html;charset=UTF-8"%>
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="utf-8">
<title>文件上传</title>
<%-- <script type="text/javascript" src="${ctx}/pc-rs/novatar.frameimpl/scripts/static/js/lib/jquery-1.9.0.min.js"></script> --%>
<script type="text/javascript" src="${contextPath}/pc-rs/novatar.frameimpl/scripts/static/js/lib/ajaxfileupload.js"></script>
<script type="text/javascript">
var upload = {
filetypelist:"doc|docx|xls|xlsx|pdf",
n:0, // 自增 用于生成 file id
isIE: function() {
var isIE = false;
var userAgent = navigator.userAgent; //取得浏览器的userAgent字符串
var isOpera = userAgent.indexOf("Opera") > -1;
if (userAgent.indexOf("compatible") > -1 && userAgent.indexOf("MSIE") > -1 && !isOpera) {
isIE = true;
}; //判断是否IE浏览器
return isIE;
},
param:null,
openUploadBox:function(param) {
upload.param = param;
$(".modal-back-layer").addClass("modal-show");
$(".modal-upload").addClass("modal-show");
$("#ul_upload").empty();
},
addfile:function() {
//var time = new Date().getTime(); //获取时间戳
if ( upload.isIE() ) {
$("#ul_upload").append("<li><input type=\"checkbox\" id=\"checkbox"+(++upload.n)+"\"/><input type=\"file\" name=\"file\" id=\"file"+
upload.n +"\" /></li>"); /*<span id=\"filename"+upload.n+"\"></span>*/
} else {
$("#upoload-center").append("<input style=\"width:0px;\" type=\"file\" name=\"file\" id=\"file"+
(++upload.n) +"\" οnchange=\"upload.showname()\" />");
$("#file" + upload.n).click();
}
},
doupload:function() {
var fileids = new Array();
var extError = false;
$.each($("#ul_upload input[type='checkbox']"), function() {
if (this.checked) {
var index = this.id.substring(8); // 截取 checkbox1 后面的 index
var filename = $("#file" + index).val();
var extname = filename.substring(filename.lastIndexOf(".") + 1);
if(upload.filetypelist.indexOf(extname) == -1 ) {
alert(extname +"类型的文件不能上传!");
extError = true;
upload.close();
}
fileids.push("file" + index);
}
});
if (extError) {
return false;
}
if ( fileids.length == 0 ){
alert("请选择文件!");
return;
}
//alert("fileids ==> " + JSON.stringify(fileids)) ;
var holdbackNo = $("input[name='holdbackNo']").val();
$.ajaxFileUpload({
url : "${contextPath}/service/ajaxfileupload",
secureuri : false,
fileElementId :fileids,//文件上传域的ID
data : {
formFileName : "file",
businessType : upload.param.businessType,
businessId : upload.param.businessId
},
dataType : 'text/html', //返回值类型 一般设置为json
success : function(data) {
var result = JSON.parse(data);
if (result.status == 1) {
alert("上传成功!");
upload.popresult({result:"success"});
} else {
alert("上传失败!");
upload.popresult({result:"fail"});
}
upload.close();
//alert("data success:" + JSON.stringify(eval( "("+data+")"));
},
error : function(data) {
alert("上传失败:" + JSON.stringify(data));
}
});
},
close : function() {
$(".modal-back-layer").removeClass("modal-show");
$(".modal-upload").removeClass("modal-show");
},
showname: function () {
if (upload.isIE()) {
var filename = $("#file" + upload.n ).val();
filename = filename.substr(filename.lastIndexOf("\\") + 1);
$("#filename" + upload.n ).html(filename);
} else {
$("#ul_upload").append("<li><input type=\"checkbox\" id=\"checkbox"+upload.n+"\"/><span id=\"filename"+upload.n+"\"></span></li>");
var filename = $("#file" + upload.n ).val() ;
filename = filename.substr(filename.lastIndexOf("\\") + 1);
$("#filename" + upload.n ).html(filename);
}
},
showfiles:function(param) {
$(".modal-back-layer").addClass("modal-show");
$(".modal-upload-files").addClass("modal-show");
var params = "needcontrolprocess:"+"attachmentUploadService.queryAttachmentUploadByBusiness|";
params += "businessType:" + param.businessType + "|";
params += "businessId:" + param.businessId + "|";
params += "effective:" + 1; //只取有效的
var url = "${contextPath}/service/pageReq?random=" + Math.random();
$.ajax({
url: url,
type : 'post',
dataType : "json",
data: {
needcontrolprocess : "attachmentUploadService.queryAttachmentUploadByBusiness",
content : params
},
success: function (result) {
var attachmentList = result.expData.attachmentList;
$.each(attachmentList , function() {
var att_id = this.id;
$("#ul_upload_files").append("<li><a href=\"${contextPath}/service/filedownload?relativeUrl="+this.relativeUrl+"&origName="+this.origName+"\">"+ this.origName+"</a>    <input type=\"button\" οnclick=\"upload.filedel( this,'"+ att_id +"');\" value=\"X\" /></li>");/*<input type=\"button\" οnclick=\"upload.filedel(\""+ this.id+"\")\">*/
});
}
});
},
filesclose : function() {
$("#ul_upload_files").empty();
$(".modal-back-layer").removeClass("modal-show");
$(".modal-upload-files").removeClass("modal-show");
},
popresult : function ( data ) {},
allchoose : function (check){
$.each($("#ul_upload input[type='checkbox']"), function() {
this.checked = check;
});
},
filedel : function( btn , id ) {
var params = "needcontrolprocess:"+"attachmentUploadService.updateByPrimaryKeySelective|";
params += "id:" + id; //只取有效的
var url = "${contextPath}/service/pageReq?random=" + Math.random();
$.ajax({
url: url,
type : 'post',
dataType : "json",
data: {
needcontrolprocess : "attachmentUploadService.updateByPrimaryKeySelective",
content : params
},
success: function (result) {
//var updateStatus = result.expData.updateStatus;
$(btn).parent().remove();
//alert("删除成功!");
}
});
}
};
$(function(){
var businessid = $("#businessid").val();
if ( businessid != null && businessid != "") {
$(".modal-back-layer").addClass("modal-show");
$(".modal-upload-files").addClass("modal-show");
}
});
</script>
<style type="text/css">
input[type="file"]::-webkit-file-upload-button {
display: none;
width: 0px;
}

.modal-back-layer {
position: fixed;
top: 0px;
left: 0px;
opacity: 0.4;
background-color: #fff;
visibility: hidden;
width: 100%;
height: 100%;
max-width: 100%;
max-height: 100%;
}

.modal-upload, .modal-upload-files {
position: fixed;
top: 30%;
left: 30%;
width: 40%;
height: 40%;
border: 1px solid #999;
background-color: #aaa;
visibility: hidden;
}

.modal-show {
visibility: visible;
}

.upoload-title {
height: 30px;
width: 100%;
padding-top: 5px;
margin: 0 auto;
font-size: 14px;
line-height: 30px;
vertical-align: middle;
background: #595F71;
color: #FFF;
border-radius: 2px;
}

.upoload-center {
height: 82%;
width: 100%;
font-size: 14px;
overflow: auto;
/* opacity: 0.9;
*/}

.upoload-center-files {
height: 82%;
width: 100%;
font-size: 14px;
overflow: auto;
}

.upoload-footer {
height: 30px;
width: 100%;
padding-top: 5px;
font-size: 14px;
line-height: 30px;
vertical-align: middle;
background: #595F71;
color: #FFF;
border-radius: 2px;
float:right;
/* padding-left: 340px; */
}

.upoload-footer-files {
height: 30px;
width: 100%;
padding-top: 5px;
font-size: 14px;
line-height: 30px;
vertical-align: middle;
background: #595F71;
color: #FFF;
border-radius: 2px;
float:right;
font-size: 14px;
}
.upoload-footer-files input {
float:right;
}


.modal-upload-inner {
margin: 0px;
height: 100%;
width: 100%;
background-color: #fff;
}

.modal-upload-inner-files {
margin: 0px;
height: 100%;
width: 100%;
background-color: #fff;
}

.upload-button {
font-size: 14px;
background-color: #aaa;
margin-left: 110px;
margin-top: 4px;
}

.choose-button {
width: 80px;
font-size: 14px;
margin-left: 20px;
margin-top: 4px;
}

.cancel-button {
font-size: 14px;
margin-left: 20px;
margin-top: 4px;
}

.ul_upload {
margin-top: 10px;
}

.ul_upload li {
height: 36px;
margin-left: 10px;
}
.all-chk {
margin-left: 10px;
}
.table-fn {
height: 30px;
line-height: 30px;
vertical-align: middle;
background: #595F71;
color: #FFF;
padding: 0 20px;
border-radius: 2px;
}
</style>
</head>

<body>
<input type="hidden" name="businessid" id="businessid" value="${ businessid }">

<div class="modal-back-layer"></div>

<div class="modal-upload" id="modal-upload">
<div class="modal-upload-inner">
<div class="upoload-title">
<center>
文件上传
</center>
</div>
<div class="upoload-center" id="upoload-center">
<ul id="ul_upload" class="ul_upload"></ul>
</div>
<div class="upoload-footer">
<input type="checkbox" value="全选" class="all-chk" οnclick="upload.allchoose(this.checked);">全选 <!-- class="btn_gray m-r15" -->
<input type="button" value="请选择文件" class="choose-button btn_gray m-r15" οnclick="upload.addfile();"> <!-- class="choose-button btn_gray m-r15" -->
<input type="button" value="上传" class="upload-button btn_gray m-r15" οnclick="upload.doupload();"> <!-- class="upload-button btn_gray m-r15" -->
<input type="button" value="取消" class="cancel-button btn_gray m-r15" οnclick="upload.close();"> <!-- class="cancel-button btn_gray m-r15" -->
</div>
</div>
</div>

<div class="modal-upload-files" id="modal-files">
<div class="modal-upload-inner-files">
<div class="upoload-title">
<center>
文件详情
</center>
</div>
<div class="upoload-center-files">
<ul id="ul_upload_files" class="ul_upload"></ul>
</div>
<div class="upoload-footer-files">
<input type="button" class="cancel-button btn_gray m-r15" value="关闭" οnclick="upload.filesclose()">
</div>
</div>
</div>
</body>
</html>

//js代码//
jQuery
.extend({
createUploadIframe : function(id, uri) {
// create frame
var frameId = 'jUploadFrame' + id;
if (window.ActiveXObject) {
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>');
if(typeof(fileElementId) == 'string'){
fileElementId = [fileElementId];
}
for(var i in fileElementId){
var oldElement = jQuery('#' + fileElementId[i]);
var newElement = jQuery(oldElement).clone();
jQuery(oldElement).attr('id', fileId);
jQuery(oldElement).before(newElement);
jQuery(oldElement).appendTo(form);
}
/* if ( fileElementId instanceof Array ) {
for(var i in fileElementId){
var oldElement = jQuery('#' + fileElementId[i]);
var newElement = jQuery(oldElement).clone();
jQuery(oldElement).attr('id', fileId);
jQuery(oldElement).before(newElement);
jQuery(oldElement).appendTo(form);
}
} else {
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;
},
addOtherRequestsToForm : function(form, data) {
// add extra parameter
var originalElement = $('<input type="hidden" name="" value="">');
for ( var key in data) {
name = key;
value = data[key];
var cloneElement = originalElement.clone();
cloneElement.attr({
'name' : name,
'value' : value
});
$(cloneElement).appendTo(form);
}
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);
if (s.data)
form = jQuery.addOtherRequestsToForm(form, 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 {
$(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() {
}
};

},

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

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();
//alert($('param', data).each(function(){alert($(this).attr('value'));}));
return data;
}
})


/**
* 文件上传
* @param request
* @param response
* @throws IOException
*/
@RequestMapping("/ajaxfileupload")
public void ajaxfileupload(HttpServletRequest request, HttpServletResponse response)
throws IOException {
response.setContentType("text/html;charset=utf-8");
String createId = UserUtil.getCurrentUser()==null?"":UserUtil.getCurrentUser().getCreateId();
String uploadBasePath = (String)request.getServletContext().getAttribute("upload.basePath");
logger.info("uploadBasePath : " + uploadBasePath);
Map<String,Object> responseMap = new HashMap<String, Object>(2);
PrintWriter out = response.getWriter();
// request 对象 转化为 MultiPartRequestWrapper类型
MultiPartRequestWrapper req = (MultiPartRequestWrapper)request;
String formFileName = request.getParameter("formFileName");
String businessType = request.getParameter("businessType");
String businessId = request.getParameter("businessId");
String dirpath = uploadBasePath + File.separator + businessType;
if ( !new File(dirpath).exists() ) {
new File(dirpath).mkdir();
}
File[] files = req.getFiles(formFileName);
FileInputStream fis = null ;
FileOutputStream fos = null;
if ( files.length <= 0 ) { // 判断文件是否存在
responseMap.put("status", Constants.FAIL);
responseMap.put("reason", "找不到文件!");
} else {
logger.info("上传文件数量" + files.length );
try {
for ( int i = 0 ; i < files.length ; i ++) {
String origName = req.getFileNames(formFileName)[i];
//String fileName = System.currentTimeMillis() + "_" + origName;
String fileName = UUID.randomUUID() + origName.substring(origName.lastIndexOf(".")) ;
fis = new FileInputStream(files[i]);
fos = new FileOutputStream(
new File(uploadBasePath + File.separator + businessType + File.separator + fileName));
byte[] bytes = new byte[1024];
int n = 0 ;
while( ( n = fis.read(bytes)) > 0){
fos.write(bytes,0,n);
}
logger.info("生成文件: " + uploadBasePath + File.separator + businessType + File.separator + fileName);
responseMap.put("status", Constants.SUCCESS);
responseMap.put("filename",fileName);
AttachmentUpload att= new AttachmentUpload();
att.setId(UUIDGenerator.getUUID());
att.setEffective(Constants.ATTA_EFFECTIVE_YES_STR);
att.setBusinessId(businessId);
att.setBusinessType(businessType);
att.setFileName(fileName);
att.setOrigName(origName);
att.setRelativeUrl(businessType + File.separator + fileName);
att.setUploadTime(new Date());
att.setUploadBy(createId);
attachmentDao.insertSelective(att);
logger.info("附件信息保存成功:" + " businessId : " + businessId + ",businessType : " + businessType);
}
} catch (Exception e) {
logger.info("文件传送失败: " + e.getMessage()) ;
responseMap.put("status", Constants.FAIL);
responseMap.put("reason", "文件传送失败!");
e.printStackTrace();
throw e ;
} finally {
fis.close();
fos.close();
}
}
logger.info("文件传送成功!");
out.println(JSON.toJSONString(responseMap));
}


/**
* 文件下载
* @param request
* @param response
* @throws IOException
*/
@RequestMapping("/filedownload")
public void filedownload(HttpServletRequest request,
HttpServletResponse response) throws IOException {
OutputStream out = null;
InputStream in = null;
String relativeUrl = null;
String origName = null;
try {
response.reset();
// 获取相对路径
relativeUrl = request.getParameter("relativeUrl");
origName = request.getParameter("origName");
logger.info("文件下载开始 : " + relativeUrl);
// 获取根目录
String uploadBasePath = (String) request.getServletContext()
.getAttribute("upload.basePath");
logger.info("uploadBasePath : " + uploadBasePath);
// 获得请求文件名
//String filename = relativeUrl.substring(relativeUrl
// .lastIndexOf("\\") + 1);
//logger.info("filename : " + filename);
// 设置文件MIME类型
// 设置Content-Disposition
response.setHeader("Content-Disposition", "attachment;filename="
+ origName);
// 读取目标文件,通过response将目标文件写到客户端
// 获取目标文件的绝对路径
String fullFileName = uploadBasePath + File.separator + relativeUrl;
response.setContentType(Files.probeContentType(Paths
.get(fullFileName)));
response.addHeader("Content-Length", "" + new File(fullFileName).length());
logger.info("文件名称 :" + fullFileName);
// System.out.println(fullFileName);
// 读取文件
out = response.getOutputStream();

in = new FileInputStream(fullFileName);
// 写文件
byte[] buffer = new byte[in.available()];
in.read(buffer);
out.write(buffer);
out.flush();
out.close();
// int b = 0;
// while ((b = in.read(buffer)) > 0) {
// out.write(buffer, 0, b);
// }
} catch (Exception e) {
e.printStackTrace();
logger.info("文件下载失败 !" + e.getMessage());
throw e;
} finally {
in.close();
}
logger.info("文件下载结束: " + relativeUrl);
}


//附件实体类-------------------------------------------------------
package com.sf.novatar.plf.bean;

import java.io.Serializable;
import java.util.Date;

public class AttachmentUpload implements Serializable {
private String id;

private String relativeUrl;

private String fileName;

private String uploadBy;

private Date uploadTime;

private String updateBy;

private Date updateTime;

private String description;

private String effective; // 1 有效 0 无效

private String businessType;

private String businessId;

private String remark;

private String origName;

private static final long serialVersionUID = 1L;

public String getId() {
return id;
}

public void setId(String id) {
this.id = id;
}

public String getRelativeUrl() {
return relativeUrl;
}

public void setRelativeUrl(String relativeUrl) {
this.relativeUrl = relativeUrl == null ? null : relativeUrl.trim();
}

public String getFileName() {
return fileName;
}

public void setFileName(String fileName) {
this.fileName = fileName == null ? null : fileName.trim();
}


public Date getUploadTime() {
return uploadTime;
}

public void setUploadTime(Date uploadTime) {
this.uploadTime = uploadTime;
}


public Date getUpdateTime() {
return updateTime;
}

public void setUpdateTime(Date updateTime) {
this.updateTime = updateTime;
}

public String getDescription() {
return description;
}

public void setDescription(String description) {
this.description = description == null ? null : description.trim();
}

public String getEffective() {
return effective;
}

public void setEffective(String effective) {
this.effective = effective == null ? null : effective.trim();
}

public String getBusinessType() {
return businessType;
}

public void setBusinessType(String businessType) {
this.businessType = businessType;
}

public String getBusinessId() {
return businessId;
}

public void setBusinessId(String businessId) {
this.businessId = businessId;
}

public String getRemark() {
return remark;
}

public void setRemark(String remark) {
this.remark = remark == null ? null : remark.trim();
}

public String getOrigName() {
return origName;
}

public void setOrigName(String origName) {
this.origName = origName == null ? null : origName.trim();
}

public String getUploadBy() {
return uploadBy;
}

public void setUploadBy(String uploadBy) {
this.uploadBy = uploadBy;
}

public String getUpdateBy() {
return updateBy;
}

public void setUpdateBy(String updateBy) {
this.updateBy = updateBy;
}

}
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值