jQuery-File-Upload java实现
来源:互联网 发布:大数据的主要来源 编辑:程序博客网 时间:2024/06/06 05:14
最近突然安排了一个实现文件上传的任务给我,啊~~接到任务后,作为实习生的我甚是惶恐~
然后就找到jQuery-File-Upload上传插件,API地址,总之,现在实现了最简单的功能~(菜鸟级别,就是记录一下)~(java部分不是我实现的)~
css
.jquery-fileupload .uploadBtn { width: 64px; height: 36px; line-height: 28px; overflow: hidden; position: relative; float: left; margin-right: 10px; } .jquery-fileupload .uploadBtn input[type="file"] { width: 60px; height: 28px; position: absolute; left: 0; top: 0; z-index: 2; opacity: 0; filter: alpha(opacity=0); } .jquery-fileupload .uploadBtn span { display: block; width: 60px; height: 28px; position: absolute; left: 0; top: 0; line-height: 28px; text-align: center; color: #ffffff; text-decoration: none; border-radius: 8px; box-shadow: 0px 1px 3px #666666; text-shadow: 1px 1px 3px #666666; border: 2px solid #4cae4c; background: #5cb85c; } .jquery-fileupload .tips{ color: #a94442; line-height: 28px; } .jquery-fileupload .filesName { width: 100%; } .jquery-fileupload table { width: 100%; } .jquery-fileupload .filesName tr { width: 100%; } .jquery-fileupload .filesName td { width: 50%; padding-left: 20px; } .jquery-fileupload .filesName .delete, .jquery-fileupload .filesName .download { color: #ffffff; padding: 2px 6px; text-decoration: none; border-radius: 8px; box-shadow: 0px 1px 3px #666666; text-shadow: 1px 1px 3px #666666; border: 1px solid #1f79b6; background: #3498db; } .jquery-fileupload .filesName .bar { height: 18px; background: green; } .jquery-fileupload .filesName .error { font-size: 16px; color: #a94442; }
html
<div class="jquery-fileupload"> <div class="uploadBtn"> <input id="fileupload" type="file" name="Filedata" multiple /> <span>+选择文件</span> </div> <span class="tips"></span> <div style="clear: both;"></div> <!--文件--> <table> <tbody class="filesName"> </tbody> </table></div>
js
需要引入的最近本的js文件(在这之前请先引入jQuery)<script src="../js/jquery.fileupload.js/jquery.ui.widget.js" charset="UTF-8" type="text/javascript"></script><script src="../js/jquery.fileupload.js/jquery.iframe-transport.js" charset="UTF-8" type="text/javascript"></script><script src="../js/jquery.fileupload.js/jquery.fileupload.js" charset="UTF-8" type="text/javascript"></script>$('#fileupload').fileupload({ url:'${app}/app/upload/fileUpload_upload.shtml?path=trade_structure&creator=${USERINFO.userId}', autoUpload:true, sequentialUploads: true, add: function(e, data) { var filename = data.files[0].name; var fileListLenght = $('.filesName').find('tr').length; for (var i = 0; i < fileListLenght; i++) { if (filename == $('.filesName').find('.name').eq(i).text()) { $('.tips').text("不能重复上传!"); return false; } } filesList = "filesList" + fileListLenght; var filesListHTML = '<tr class="' + filesList + '">' + '<td>' + '<p class="name">' + filename + '</p>' + '<div class="progress">' + '<div class="bar" style="width: 0%;"></div>' + '</div>' + '<strong class="error"></strong>' + '</td>' + '</tr>'; $('.filesName').append(filesListHTML); data.context = $("." + filesList); data.submit(); }, //单个进度条 progress: function(e, data) { var progress = parseInt(data.loaded / data.total * 100, 10); data.context.find('.bar').css('width', progress + '%'); }, //上传失败 fail: function(e, data) { data.context.find('.error').text('上传失败'); } //上传完成 done : function(e, data) { $('.filesName').find('.progress').parent().parent().remove(); $.each(data.files, function (index, file) { var res = data.result.split(","); if(res[0] == "success:"){ var filesList = "filesList" + $('.filesName').find('tr').length; var filesListHTML ='<tr class="' + filesList + '">' + '<td>' + '<p class="name">' + res[3] + '</p>' + '</td>' + '<td class="btns">' + '<button class="delete">删除</button> ' + '<button class="download">下载</button>' + '</td>' + '</tr>'; $(".filesName").append(filesListHTML); $("."+filesList).find('.delete').click(function(){ window.location.hash='#top'; $.messager.confirm("信息提示","请注意,删除的附件将无法恢复,是否确认删除?",function(b){ if(b){ $.ajax({ async:false, type:'post', url:'${app}/app/upload/fileUpload_delAttachment.shtml', dataType:'html', data:'id=' + res[2], success:function(msg){ $("."+filesList).remove(); } }); } window.location.hash='#bottom'; }); }); $("."+filesList).find('.download').click(function(){ downloadFile(res[1],res[3]); }); } }); } });
downloadFile函数
/** * 附件下载 * @param {Object} path 路径 * @param {Object} fileName 文件名 */ function downloadFile(path,fileName){ if(getOs() == "Firefox"){ window.location.href="${app}/download.shtml?path=" + path +"&fileName="+fileName; }else{ window.location.href="${app}/download.shtml?path="+encodeURIComponent(encodeURIComponent(path))+"&fileName="+encodeURIComponent(encodeURIComponent(fileName)); } }
fileUploadAction.java
import java.io.File;import java.io.FileNotFoundException;import java.io.InputStream;import java.util.HashMap;import java.util.List;import java.util.Map;import net.sf.json.JSONSerializer;import org.apache.commons.io.FileUtils;import org.springframework.beans.factory.annotation.Autowired;import org.springframework.context.annotation.Scope;import org.springframework.stereotype.Controller;/** * * Description: 文件上传action * @version 1.0 * </pre> */@Controller("fileUploadAction")@Scope("prototype")public class FileUploadAction extends MisAction { @Autowired private AttachmentService attachmentService; private File Filedata; // 上传上来的文件(与<input id="fileupload" type="file" name="Filedata" multiple /> name相同) private String FiledataContentType; // 上传的文件类型,这里不做考虑,因为前台已经验证过了 private String FiledataFileName; // 上传上来的文件名 private static final String FOLDER_NAME = "NwmssUploadFile"; private String path; // 文件保存的文件夹,这是action传过来的参数 private Long id; //附件ID private Long creator;//创建人 private String remark; private String objectType; private String Filename; private String Upload; /** * 参照对象ID */ private Long objectId; @Autowired private AdvancePaymentService advancePaymentService; private String browserVersion;//浏览器类型 private String productId; //上传的附件,以逗号隔开的展现形式 public String getBrowserVersion() { return browserVersion; } public void setBrowserVersion(String browserVersion) { this.browserVersion = browserVersion; } public String getProductId() { return productId; } public void setProductId(String productId) { this.productId = productId; } public File getFiledata() { return Filedata; } public void setFiledata(File filedata) { Filedata = filedata; } public String getFiledataContentType() { return FiledataContentType; } public void setFiledataContentType(String filedataContentType) { FiledataContentType = filedataContentType; } public String getFiledataFileName() { return FiledataFileName; } public void setFiledataFileName(String filedataFileName) { FiledataFileName = filedataFileName; } public Long getId() { return id; } public void setId(Long id) { this.id = id; } public String getPath() { return path; } public void setPath(String path) { this.path = path; } public Long getCreator() { return creator; } public void setCreator(Long creator) { this.creator = creator; } public String getRemark() { return remark; } public void setRemark(String remark) { this.remark = remark; } public Long getObjectId() { return objectId; } public void setObjectId(Long objectId) { this.objectId = objectId; } /** * Description: 上传 * * @param * @return String * @throws Exception */ public String upload() throws Exception { try { String attchmentFileType = new String(path); //附件类型 path = "/" + FOLDER_NAME + "/" + path + "/" + DateTimeUtil.getNowYearMonthString(); File target = new File(getAttachmentPath() + path); if(!target.exists()){ target.mkdirs(); } String newName = FileRenameUtil.getNewFileName(FiledataFileName); //为防止图片名称一样产生的覆盖问题,对图片重新命名 File newFile = new File(target,newName); //根据 target路径名字符串和 newName 路径名字符串创建一个新 File 实例。 FileUtils.copyFile(Filedata, newFile); String newFilePath = path + "/" + newFile.getName(); Attachment attachment = new Attachment(); if(remark!=null && !remark.trim().equals("")){ attachment.setRemark(remark); } attachment.setName(FiledataFileName); attachment.setPath(newFilePath); attachment.setFileType(attchmentFileType); attachment.setObjectType(objectType); attachment.setObjectId(objectId); attachment.setCreator(creator); long attachmentId = attachmentService.insert(attachment); response.setContentType("text/html"); response.setCharacterEncoding("UTF-8"); response.getWriter().write("success:" + "," + newFilePath + "," + attachmentId + ","+ FiledataFileName); } catch (Exception e) { logger.info("系统异常:" + e.getMessage(),e); //e.printStackTrace(); response.setCharacterEncoding("UTF-8"); response.getWriter().write("error:上传文件失败!"); } return null; } /** * Description: 上传到影像平台 * * @param * @return String * @throws Exception */ public String uploadfdfs() throws Exception { try { String attchmentFileType = new String(path); //附件类型 path = "/" + FOLDER_NAME + "/" + path + "/" + DateTimeUtil.getNowYearMonthString(); File target = new File(getAttachmentPath() + path); if(!target.exists()){ target.mkdirs(); } String newName = FileRenameUtil.getNewFileName(FiledataFileName); //为防止图片名称一样产生的覆盖问题,对图片重新命名 File newFile = new File(target,newName); //根据 target路径名字符串和 newName 路径名字符串创建一个新 File 实例。 FileUtils.copyFile(Filedata, newFile); //String newFilePath = path + "/" + newFile.getName(); //先上传的影像平台,成功后再插入数据库 FdfsFile fdfsFile = new FdfsFile(); fdfsFile.setProjectCode("projectId");//项目id fdfsFile.setProjectName("project"); //fdfsFile.setTypeCode("jpg"); //fdfsFile.setTypeName("JPC"); fdfsFile.setFilePath(newFile.getCanonicalPath()); fdfsFile.setFileName(FiledataFileName); String fileNo = FdfsManager.upload(fdfsFile); //上传成功后删除本地文件,注意在生产上是否允许删除 newFile.delete(); String fileUrl = FdfsManager.query(fileNo); String fdfsFilePath = fileUrl; Attachment attachment = new Attachment(); if(remark!=null && !remark.trim().equals("")){ attachment.setRemark(remark); } attachment.setName(FiledataFileName); attachment.setPath(fdfsFilePath); attachment.setFileType(attchmentFileType); attachment.setObjectType(objectType); attachment.setObjectId(objectId); attachment.setCreator(creator); attachment.setFdfsFileno(fileNo);; long attachmentId = attachmentService.insert(attachment); response.setContentType("text/html"); response.setCharacterEncoding("UTF-8"); response.getWriter().write("success:" + "," + fdfsFilePath + "," + attachmentId + ","+ FiledataFileName); //前端需要返回文件号fileno用于删除,数据库也需要记录文件号,用户查看,删除影像文件 } catch (Exception e) { logger.info("系统异常:" + e.getMessage(),e); //e.printStackTrace(); response.setCharacterEncoding("UTF-8"); response.getWriter().write("error:上传文件失败!"); } return null; } /** * Description: 删除附件(包括影像系统的文件) * * @param * @return String * @throws Exception */ public String delAttachment() throws Exception { try { Attachment attachment = attachmentService.selectByPrimaryKey(id); attachmentService.deleteByPrimaryKey(id); if (attachment.getFdfsFileno()!=null) { FdfsManager.delete(attachment.getFdfsFileno()); } response.setContentType("text/html"); response.setCharacterEncoding("UTF-8"); response.getWriter().write("删除成功"); } catch (Exception e) { logger.info("系统异常:" + e.getMessage(),e); //e.printStackTrace(); response.getWriter().write("删除失败"); } return null; } public String getObjectType() { return objectType; } public void setObjectType(String objectType) { this.objectType = objectType; } public String getFilename() { return Filename; } public void setFilename(String filename) { Filename = filename; } public String getUpload() { return Upload; } public void setUpload(String upload) { Upload = upload; }}
效果如下:
1 1
- jQuery-File-Upload java实现
- jquery upload file
- jQuery File Upload
- jQuery File Upload
- Backload jquery file upload
- jQuery File Upload
- jQuery File Upload
- jQuery File Upload
- jQuery-file-upload随笔
- jQuery File Upload
- Jquery File Upload 入门
- jQuery-file-upload随笔
- jquery-file-upload
- jQuery file upload file 总结
- jQuery file upload实现异步文件上传(带进度条)
- jQuery Multiple File Upload Plugin
- Rails Carrierwave JQuery File Upload
- jquery upload file demo (C#)
- 学习笔记——shell命令(2)AWK
- 国际化: 理解Java平台下的Locale
- 仿照CIFAR-10数据集格式,制作自己的数据集
- iOS 分层架构设计
- 缓存之redis
- jQuery-File-Upload java实现
- mysql查询结果按中文字母排序
- 机器学习正则化(Regularization)
- SharedPreferences的使用
- Multipy String | leetcode
- 开头第一篇
- block作用
- Window和view的关系
- 数据库常用SQL总结