javascript代码实例教程-jersey(rest)架构实现上传下载

发布时间:2019-03-30 发布网站:脚本宝典
脚本宝典收集整理的这篇文章主要介绍了javascript代码实例教程-jersey(rest)架构实现上传下载脚本宝典觉得挺不错的,现在分享给大家,也给大家做个参考。
小宝典致力于为广大程序猿(媛)提供高品质的代码服务,请大家多多光顾小站,小宝典在此谢过。

其实是先的是最简单的上传下载,也是最古老的方法,其实我觉得好的地方是存在一个flash效果,

 


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">
<p 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>
<p id="file_upload"></p>
<p id="file_list"></p>
</li>
</ul>
</p>
<p class="BTn_p">
<input type="button" class="Btn_save" value="上&nbsp;传" onclick="$(&#39;#file_upload').uploadifyUpload();" id="saveArea"/>
<input type="button" class="Btn_save" value="保&nbsp;存" onclick="savePlacard()" id="saveArea"/><input type="button" class="Btn_cancle" onclick="closeWin()" value="取&nbsp;消" id="exitArea"/>
</p>
</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"]+"/">&nbsp;</a>";
createDate=data[i]["createDate"];
if(createDate!=null && createDate!=""){
createDate=createDate.substring(0,11);
}
html=html+"<label class=/"fr/">"+createDate+"</label>";

html=html+"<p 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+="</p></li>";
}
$("#notice").html(html);
$("#notice li").click(function(){
$("p",$(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();
        }
}

 

 

 


 

觉得可用,就经常来吧! 脚本宝典 欢迎评论哦! js脚本,巧夺天工,精雕玉琢。小宝典献丑了!

脚本宝典总结

以上是脚本宝典为你收集整理的javascript代码实例教程-jersey(rest)架构实现上传下载全部内容,希望文章能够帮你解决javascript代码实例教程-jersey(rest)架构实现上传下载所遇到的问题。

如果觉得脚本宝典网站内容还不错,欢迎将脚本宝典推荐好友。

本图文内容来源于网友网络收集整理提供,作为学习参考使用,版权属于原作者。
如您有任何意见或建议可联系处理。小编QQ:384754419,请注明来意。