Uploadify上傳和最原始的下載

上傳是用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="上&nbsp;傳" onclick="$('#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"/>
</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"]+"\">&nbsp;</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  



發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章