上传是用Uploadify实现的,下载是最原始的方式写的
html页面:
引入了 <script type="text/javascript" src="$stylePath/resources/js/swfobject.js"></script>
<script type="text/javascript" src="$stylePath/resources/js/jquery.uploadify.v2.1.0.min.js"></script>
<link rel="stylesheet" href="$stylePath/resources/styles/uploadify.css" type="text/css" media="screen"/>
<body>
<form id="userForm" method="post">
<div class="wrap_item">
<input id="id" name="id" type="hidden"/>
<ul>
<li>
<label>标题:</label>
<input type="text" id="title" name="title" class="js_area"/>
</li>
<li>
<label>描述:</label>
<textarea rows="" cols="" id="description" name="description"></textarea>
<span class="text">文本长度限制200个字符</span>
<input type="hidden" name="filePath" id="filePath"/>
<input type="hidden" name="fileNameSystem" id="fileNameSystem"/>
<input type="hidden" name="fileNameActual" id="fileNameActual"/>
</li>
<li>
<label>文件</label>
<div id="file_upload"></div>
<div id="file_list"></div>
</li>
</ul>
</div>
<div class="btn_div">
<input type="button" class="Btn_save" value="上 传" onclick="$('#file_upload').uploadifyUpload();" id="saveArea"/>
<input type="button" class="Btn_save" value="保 存" onclick="savePlacard()" id="saveArea"/><input type="button" class="Btn_cancle" onclick="closeWin()" value="取 消" id="exitArea"/>
</div>
</form>
</body>
js代码:
$(function(){
$('#file_upload').uploadify({
'uploader' : '$stylePath/resources/imgs/uploadify.swf',
'script' : $().getRealPath()+'/ccms/placard/placard/upload',
'fileDataName' : 'file',
'cancelImg' : '$stylePath/resources/imgs/cancel.png',
'multi' : false,
'onComplete': function(event, queueID, fileObj, response, data) {
$(this).each(function(i) {
var strs=response;
//strs=strs.substring(1,strs.indexOf("]"));
strs=strs.replace("/\'/g","");
strs=strs.replace("/\"/g","");
var str=strs.split(",");
$("#filePath").val(str[0]);
$("#fileNameSystem").val(str[1]);
$("#fileNameActual").val(str[2]);
});
},
'onAllComplete': function(event, data) {
$("#file_list").html("本次上传文件: " + data.filesUploaded + " 个,文件总大小: " + data.allBytesLoaded + " KB,平均上传速度: " + data.speed + "kb/s");
},
'onError': function(event, queueID, fileObj) {
alert("文件:" + fileObj.name + " 上传失败");
}
});
});
save方法
function savePlacard(){
if(!check())return false;
$("#userForm").attr("action",$().getRealPath()+"/ccms/placard/placard/add");
$("#userForm").ajaxSubmit({
success:function(responseText,statusText,xhr,$form){
if(responseText=="1"){
alert("保存失败");
}
else{
confirm("保存成功",function (){
$("#id").val(responseText);
art.dialog.data("state","y");
art.dialog.data("origin").close();
});
}
}
});
后台资源方法
@POST
@Produces("text/plain")
@Path("/upload")
public String load(@Context HttpServletRequest request) throws Exception {
request.setCharacterEncoding("UTF-8");
String fileName ="";
String fileNewName="";
String fileRepository =request.getSession().getServletContext().getRealPath("")+ File.separatorChar+"upload"+File.separatorChar;
String filePath=File.separatorChar+"upload"+File.separatorChar;
String fileType="";
if (ServletFileUpload.isMultipartContent(request)) {
FileItemFactory factory = new DiskFileItemFactory();
ServletFileUpload upload = new ServletFileUpload(factory);
List<FileItem> items = null;
try {
items = upload.parseRequest(request);
} catch (FileUploadException e) {
e.printStackTrace();
}
if (items != null) {
Iterator<FileItem> iter = items.iterator();
while (iter.hasNext()) {
FileItem item = iter.next();
if (!item.isFormField() && item.getSize() > 0) {
fileName = processFileName(item.getName());
fileType=getFileType(fileName);
fileNewName=getFileName(fileName)
+new SimpleDateFormat("yyyyMMddHHmmssSSS") .format(new Date() )+fileType;
fileRepository=fileRepository+fileNewName;
filePath=filePath+fileNewName;
try {
item.write(new File(fileRepository));
} catch (Exception e) {
e.printStackTrace();
}
}
}
}
}
return fileRepository + ","+fileNewName+","+fileName;
}
------------------------------------------以上是上传--------------------------------------------------------
------------------------------------------以上是下载--------------------------------------------------------
下载js
//获取上传的文件列表,这个在不同项目中是可变的
function loadPlcard(){
var html="";
$.post($().getRealPath()+"/ccms/placard/placard/protalList",{id:""},
function(data) {
if(data!=null){
var createDate="";
var filePath="";
for(var i=0;i<data.length;i++){
html=html+"<li><label id=\"title\">"+data[i]["title"];
html=html+"</label>";
html=html+"<a class=\"fr portal_notice_delete\" id=\"delete\" onclick=\"deleteNotice(this.value)\"";
html=html+" value=\""+data[i]["id"]+"\"> </a>";
createDate=data[i]["createDate"];
if(createDate!=null && createDate!=""){
createDate=createDate.substring(0,11);
}
html=html+"<label class=\"fr\">"+createDate+"</label>";
html=html+"<div style=\"display:none\">";
html=html+"<label class=\"notice_content\">"+data[i]["description"]+"</label>";
filePath=data[i]["filePath"];
if(filePath!=null && filePath!=""){
html=html+"<a class=\"portal_notice_text\" onclick=\"exportFile("+data[i]["id"]+")\">";
html=html+data[i]["fileNameActual"]+"</a>"
}
html+="</div></li>";
}
$("#notice").html(html);
$("#notice li").click(function(){
$("div",$(this)).toggle();
$("#title",$(this)).toggleClass("notice_title");
});
}
}, "json");
}
//点击要下载的文件时候,--------这个地方千万要注意,就是不要用ajaxSubmit 进行提交表单,否则会出现浏览器不会弹出下载框,在响应里面你会看到,你要
下载的东西全都成了文本流,切记
function exportFile(id){
$("#pracardId").val(id);
$("#exportForm").attr("action",$().getRealPath()+"/ccms/placard/placard/export");
//$("#exportForm").ajaxSubmit();
$("#exportForm").submit();
}
下载资源后台代码
@POST
@Path("/export")
@Consumes(MediaType.APPLICATION_FORM_URLENCODED)
@Produces({ MediaType.APPLICATION_OCTET_STREAM })
public void export(MultivaluedMap<String, String> map) throws Exception {
PlacardServiceImpl placardServiceImpl = BeanUtils.getBean(
"placardServiceImpl", PlacardServiceImpl.class);
PlacardModel model = MEJUntils.paramsInto(map, PlacardModel.class);
model = placardServiceImpl.portalPagePlacardList(model).get(0);
try {
File file = new File(model.getFilePath());
// 取得文件名。
String filename = model.getFileNameActual();
// 取得文件的后缀名。
String ext = filename.substring(filename.lastIndexOf(".") + 1).toUpperCase();
// 以流的形式下载文件。
InputStream fis = new BufferedInputStream(new FileInputStream(model.getFilePath()));
byte[] buffer = new byte[fis.available()];
fis.read(buffer);
fis.close();
// 清空response
getResponse().reset();
// 设置response的Header
getResponse().addHeader("Content-Disposition", "attachment;filename=" +java.net.URLEncoder.encode(filename, "UTF-8"));
getResponse().addHeader("Content-Length", "" + file.length());
OutputStream toClient = new BufferedOutputStream(getResponse().getOutputStream());
getResponse().setContentType("application/octet-stream");
toClient.write(buffer);
toClient.flush();
toClient.close();
} catch (IOException ex) {
ex.printStackTrace();
}
}
个人觉得 java中Uploadify 文章 这篇也比较好,
http://www.blogjava.net/yangxiang/archive/2009/07/29/288888.html