从github下载源码
https://github.com/moxiecode/plupload/tree/master/js
从百度富文本官网下载源码
https://ueditor.baidu.com/website/download.html#ueditor
附件上传下载可以参考:
API:http://www.phpin.net/tools/plupload/
https://www.sojson.com/blog/214.html
https://blog.csdn.net/wuyiwanmei/article/details/78909587
https://www.cnblogs.com/2050/p/3913184.html
-------------------------------------------前台页面---------------------------------------------------
<%@ page language="java" import="java.util.*" pageEncoding="UTF-8"%>
<%@ include file="/common/taglibs.jsp"%>
<%
String path = request.getContextPath();
String basePath = request.getScheme()+"://"+request.getServerName()+":"+request.getServerPort()+path+"/";
%>
<script>
function callback(json) {
console.log(json.row_ides)
var rowId=json.row_ides;
for(var i=0;i<rowId.length;i++){
console.log("#"+rowId[i])
$("#"+rowId[i]).remove();
}
}
$(function () {
var uploader = new plupload.Uploader({
runtimes : 'html5,flash,silverlight,html4',
//触发文件选择对话框的按钮,为那个元素id
browse_button : 'pickfiles',
//服务器端的上传页面地址
url : '<%=basePath%>weeklyreport/fileupload.do',
//swf文件,当需要使用swf方式进行上传时需要配置该参数
flash_swf_url : '../js/Moxie.swf',
//silverlight文件,当需要使用silverlight方式进行上传时需要配置该参数
silverlight_xap_url : '../js/Moxie.xap',
//是否可以在文件浏览对话框中选择多个文件
multi_selection:true,
filters : {
mime_types : [ //只允许上传图片
{ title : "Image files", extensions : "jpg,gif,png,doc,docx,pdf" }
],
max_file_size : '50mb', //最大只能上传50mb的文件
prevent_duplicates : true //不允许选取重复文件
},
init: {
PostInit: function() {
document.getElementById('uploadfiles').onclick = function() {
uploader.start();
return false;
};
},
FilesAdded:function(up,files){
plupload.each(files, function(file) {
document.getElementById('upload-file-list').value = file.name ;
});
},
FileUploaded:function(up,file,response){
console.log(JSON.parse(response.response).AttachEntity)
var user=JSON.parse(response.response).user
var AttachEntity=JSON.parse(response.response).AttachEntity
var tbBody=document.getElementById("tbBody")
var tr=document.createElement("tr")
tr.setAttribute("id", AttachEntity.rowId)
var text=null
for(var i=0;i<5;i++) {
var td = document.createElement("td")
td.setAttribute("align","center")
if(i==0){
td.innerHTML='<input type="checkbox" class="icheckbox_minimal-purple" style="bottom: 0px;" data-toggle="icheck" name="ids" value='+AttachEntity.rowId+'/>'
}
else if(i==1) {
text = document.createTextNode(file.name);
}else if(i==2){
text = document.createTextNode(file.lastModifiedDate);
}else if(i==3){
text = document.createTextNode(user.userName);
}else {
text = document.createTextNode(file.type);
}
if(i!=0){
td.appendChild(text)
}
tr.appendChild(td)
}
tbBody.appendChild(tr);
// $("#uploadfiles").bjuiajax('refreshlayout', { target:$("#tabelRe")});
// $("#uploadfiles").dialog('refresh')
},
Error: function(up, err) {
$.CurrentDialog.alertmsg("error", err.message);
}
}
});
uploader.init();
})
</script>
<base href="<%=basePath %>">
<div class="bjui-pageContent">
<form action="<%=basePath%>weeklyreport/weeklyreport-save.do" method="post" data-toggle="validate" data-reloadNavtab="true">
<input type="hidden" name="rowId" value="${weeklyReport.rowId}" >
<table class="table table-condensed table-hover">
<tbody>
<tr>
<td>
<label class="control-label x90" style="width: 105px;">时间周期:</label>
<input type="number" name="ext1" value="${weeklyReport.ext1}" >
</td>
</tr>
<tr>
<td>
<label class="control-label x90" style="width: 105px;">开始时间:</label>
<input id="startTime" type="text" name="ext2" value="${weeklyReport.ext2}" data-toggle="datepicker" data-pattern="yyyy-MM-dd HH:mm:ss" readonly="readonly" >
</td>
</tr>
<tr>
<td>
<label class="control-label x90" style="width: 105px;">结束时间:</label>
<input id="endTime" type="text" name="ext3" value="${weeklyReport.ext3}" data-toggle="datepicker" data-pattern="yyyy-MM-dd HH:mm:ss" readonly="readonly" >
</td>
</tr>
<tr>
<td>
<label class="control-label x90" style="width: 105px;">周报:</label>
<script id="container" name="thisWeekWork" type="text/plain" >
${weeklyReport.thisWeekWork }
</script>
</td>
</tr>
<tr>
<td>
<label class="control-label x90" style="width: 105px;">其他事项:</label>
<textarea name="otherWork" data-toggle="autoheight" >
${weeklyReport.otherWork}
</textarea>
</td>
</tr>
<tr>
<td>
<input type="hidden" name="bdId" value="${weeklyReport.bdId}" >
<label class="control-label x90" style="width: 105px;">标段:</label>
<input type="text" name="bdName" readonly="readonly" value="${weeklyReport.bdName}" data-toggle="lookup" data-url="<%=basePath %>risk/lookup-risk-bdId-list.do" data-title="请选择标段名称:" data-rule="required">
</td>
</tr>
<tr>
<td id="columnArticleTitlePicForm">
<table width="90%" border="0" cellspacing="0" cellpadding="0">
<tr>
<td width="15%"><label class="control-label x90" style="width: 105px;">文件名称:</label></td>
<td>
<input id="upload-file-list" size="30" readonly="readonly"/>
<button id="pickfiles" class="btn-default " data-icon="hand-pointer-o">浏览</button>
</td>
<td>
<button id="uploadfiles" class="btn-blue" data-icon="upload" >上传</button>
</td>
<td>
<button type="button" class="btn-red" data-url="<%=basePath%>weeklyreport/delete.do" data-toggle="doajaxchecked" data-confirm-msg="确定要删除选中项吗?" data-icon="remove" data-idname="delids" data-group="ids" data-callback="callback">删除选中文件</button>
</td>
<td>
<button type="button" class="btn-blue" data-url="<%=basePath%>vis/fileDownload.do" data-toggle="doexportchecked" data-confirm-msg="确定要下载吗?" data-icon="download" data-idname="delids" data-group="ids">下载选中文件</button>
</td>
</tr>
</table>
<table id="tabelRe" class="table table-bordered table-hover table-striped table-top" >
<tbody id="tbBody">
<tr>
<td width="5%" align="center"><input type="checkbox" class="checkboxCtrl" data-group="ids" data-toggle="icheck"></td>
<td align="center" width="30%">文件名称</td>
<td align="center" width="35%">上传时间</td>
<td align="center" width="15%">上传人</td>
<td align="center" width="10%">操作</td>
</tr>
<c:forEach items="${fileRecordList}" var="fileRecord" varStatus="status">
<tr id="${fileRecord.rowId}">
<td align="center"><input type="checkbox" name="ids" data-toggle="icheck" value="${fileRecord.rowId}"></td>
<td align="center">${fileRecord.fileName }</td>
<td align="center">${fileRecord.uploadTime}</td>
<td align="center">${fileRecord.uploadUserId}</td>
<td align="center">${fileRecord.fileType}</td>
</tr>
</c:forEach>
</tbody>
</table>
</td>
</tr>
</tbody>
</table>
</form>
</div>
<div class="bjui-pageFooter">
<ul>
<li><button type="button" class="btn-close">关闭</button></li>
<li><button type="submit" id="submit" class="btn-default">保存</button></li>
</ul>
</div>
<script type="text/javascript">
var editorOption = {
toolbars: [[
'fullscreen', '|', 'undo', 'redo', '|',
'bold', 'italic', 'underline', 'fontborder', 'strikethrough', 'superscript', 'subscript', 'removeformat', 'formatmatch', 'autotypeset', 'blockquote', 'pasteplain', '|', 'forecolor', 'backcolor', 'insertorderedlist', 'insertunorderedlist', 'selectall', 'cleardoc', '|',
'rowspacingtop', 'rowspacingbottom', 'lineheight', '|',
'customstyle', 'paragraph', 'fontfamily', 'fontsize', '|',
'directionalityltr', 'directionalityrtl', 'indent', '|',
'justifyleft', 'justifycenter', 'justifyright', 'justifyjustify', '|', 'touppercase', 'tolowercase', '|',
'link', 'unlink', 'anchor', '|', 'imagenone', 'imageleft', 'imageright', 'imagecenter', '|',
'simpleupload', 'insertimage', 'emotion', 'scrawl', 'insertframe', 'pagebreak', 'template', 'background', '|',
'horizontal', 'date', 'time', 'spechars', 'snapscreen', 'wordimage', '|',
'inserttable', 'deletetable', 'insertparagraphbeforetable', 'insertrow', 'deleterow', 'insertcol', 'deletecol', 'mergecells', 'mergeright', 'mergedown', 'splittocells', 'splittorows', 'splittocols', 'charts', '|',
'searchreplace', 'drafts'
]],
elementPathEnabled: false,
charset:"utf-8"
,initialFrameWidth:920 //初始化编辑器宽度,默认1000
,initialFrameHeight:500 //初始化编辑器高度,默认320
};
var ue = new baidu.editor.ui.Editor(editorOption);
ue.render("container");
ue.ready(function() {
ue.focus(true);
ue.addListener('blur',function(editor){
if(ue.hasContents()==false){
$(this).alertmsg('error', '周报不能为空,请检查!', {displayMode:'slide', displayPosition:'topcenter'})
$("#submit").attr('disabled',true);
}else{
$("#submit").attr('disabled',false);
}
});
});
</script>
----------------------------------------------后台---------------------------------------------------
-------------------------------------------fileupload---------------------------------------------------
@RequestMapping("fileupload")
@ResponseBody
public Map<String, Object> processUpload(@RequestParam MultipartFile file,
Model model, HttpSession session
) throws IOException {
Map<String, Object> resMap = new HashMap<String, Object>();
VUser user=(VUser)session.getAttribute("user_session");
resMap.put("user", user);
model.addAttribute("message", "File '" + file.getOriginalFilename());
// String bol="yes";
String fileOriginalName = file.getOriginalFilename();
String statusCode = "200", message = "上传成功";
AttachEntity attachment = new AttachEntity();
FileRecord fileRecord=new FileRecord();
try {
if (!StringUtils.isEmpty(fileOriginalName)) {
FileUtil fileHelper = new FileUtil();
String decodeFileName = fileHelper.getDecodeFileName(fileOriginalName);// 文件名编码
String mFilePath = session.getServletContext().getRealPath("") + decodeFileName; // 取得服务器路径
mFilePath = mFilePath.substring(0, 2) + "\\njdtjsis" + "\\weeklyreport\\" + decodeFileName;
fileHelper.createFile(mFilePath, file.getBytes());
fileRecord.setFilePath(mFilePath);
fileRecord.setUploadUserName(user.getUserId());
fileRecord.setUploadUserId(user.getUserName());
fileRecord.setFileName(fileOriginalName);
Timestamp time = new Timestamp(System.currentTimeMillis());
fileRecord.setUploadTime(time);
fileRecord.setFileType(file.getContentType());
fileRecord.setFileIdentifyName(decodeFileName);
fileRecordManager.save(fileRecord);
message = "请选择上传文件";
statusCode = "300";
}
} catch (Exception e) {
statusCode = "300";
message = "上传失败";
// bol="no";
e.printStackTrace();
}
resMap.put("AttachEntity", fileRecord);
if(fileRecord.getRowId()!=null) {
rowIdList.add(fileRecord.getRowId());
}
return resMap;
}
-------------------------------------------文件上传后删除---------------------------------------------------
@RequestMapping("delete")
@ResponseBody
public Map<String, Object> delete(@RequestParam String delids){
Map<String, Object> resMap = new HashMap<String, Object>();
List<String> row_ides=new ArrayList<>();
String statusCode = "200", message = "删除成功";
try {
if (delids != null && delids.length() > 0) {
String[] ids = delids.split(",");
for (String rowId : ids) {
if (rowId != null && rowId.length() > 0) {
row_ides.add(rowId);
String filePath=fileRecordManager.get(rowId).getFilePath();
FileUtil fileHelper = new FileUtil();
boolean isDelete = true;
try {
fileHelper.deleteFile(filePath);
if (!isDelete) {
statusCode = "300";
message = "删除失败";
}
} catch (Exception e) {
statusCode = "300";
e.printStackTrace();
}
fileRecordManager.removeById(rowId);
rowIdList.remove(rowId);
resMap.put("nowRowId", rowId);
}
}
}
} catch (Exception e) {
statusCode = "300";
message = "删除失败";
}
resMap.put("statusCode", statusCode);
resMap.put("message", message);
resMap.put("row_ides",row_ides);
return resMap;
}
-------------------------------------------附件下载---------------------------------------------------
@RequestMapping(value = "fileDownload")
@ResponseBody
public Map<String, Object> fileDownLoad( @RequestParam String delids, HttpServletRequest request,
HttpServletResponse response) throws IOException {
Map<String, Object> resMap = new HashMap<String, Object>();
String[] ids = delids.split(",");
for(String id:ids){
FileRecord fileRecord = fileRecordManager.get(id);
if(fileRecord!=null) {
String filePath = fileRecord.getFilePath();
String fileName = fileRecord.getFileName();
FileUtil fileHelper = new FileUtil();
fileHelper.downloadFile(filePath, request, response, fileName);
resMap.put("statusCode", "200");
resMap.put("message", "下载成功");
}else {
resMap.put("statusCode", "300");
resMap.put("message", "下载失败");
}
}
return resMap;
}
-------------------------------FileUtil封装工具类---------------------
import java.io.BufferedInputStream;
import java.io.BufferedOutputStream;
import java.io.ByteArrayOutputStream;
import java.io.DataOutputStream;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.IOException;
import java.net.URLEncoder;
import java.util.UUID;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import org.apache.commons.lang3.StringUtils;
import org.springframework.http.HttpStatus;
public class FileUtil {
/**
* decode文件名,加入时间防止有名字冲突
*
* @param fileName
* @return
*/
public String getDecodeFileName(String fileName) {
String fileStrName = "";
if (fileName != null && fileName.length() > 0) {
String[] filenames = fileName.split("\\.");
long times = DateUtil.getDate().getTime();
String fileSuffix = "";
if (filenames.length == 2) {
fileSuffix = filenames[1];
}
// fileStrName = filenames[0] + times + fileSuffix;
// fileStrName = UUID.fromString(fileStrName).toString();
fileStrName = UUID.randomUUID() + "." + fileSuffix;
}
return fileStrName;
}
// 第一种获取文件内容方式
public byte[] getContent(String filePath) throws IOException {
File file = new File(filePath);
long fileSize = file.length();
if (fileSize > Integer.MAX_VALUE) {
System.out.println("file too big...");
return null;
}
FileInputStream fi = new FileInputStream(file);
byte[] buffer = new byte[(int) fileSize];
int offset = 0;
int numRead = 0;
while (offset < buffer.length
&& (numRead = fi.read(buffer, offset, buffer.length - offset)) >= 0) {
offset += numRead;
}
// 确保所有数据均被读取
if (offset != buffer.length) {
throw new IOException("Could not completely read file "
+ file.getName());
}
fi.close();
return buffer;
}
// 第二种获取文件内容方式
public byte[] getContent2(String filePath) throws IOException {
FileInputStream in = new FileInputStream(filePath);
ByteArrayOutputStream out = new ByteArrayOutputStream(1024);
System.out.println("bytes available:" + in.available());
byte[] temp = new byte[1024];
int size = 0;
while ((size = in.read(temp)) != -1) {
out.write(temp, 0, size);
}
in.close();
byte[] bytes = out.toByteArray();
System.out.println("bytes size got is:" + bytes.length);
return bytes;
}
/**
* 将byte数组写入文件
*
* @param path
* @param content
* @throws IOException
*/
public void createFile(String path, byte[] content) throws IOException {
File file = new File(path);
if (!file.exists()) {// 文件路径不存在,创建
File pfiles = file.getParentFile();
pfiles.mkdirs();
file.createNewFile();
}
FileOutputStream fos = new FileOutputStream(file);
fos.write(content);
fos.close();
}
/**
* 删除文件
*
* @param filePath
* 文件路径
*/
/**
* 删除文件
*
* @param filePath
* 文件路径
* @return 删除成功true;失败false
*/
public boolean deleteFile(String filePath) {
File file = new File(filePath);
// 如果文件路径所对应的文件存在,并且是一个文件,则直接删除
if (file.exists() && file.isFile()) {
if (!file.delete()) {
return false;
}
}
return true;
}
/**
* 下载文件
*
* @param downLoadPath
* 下载路径
* @param response
* @param fileName
* 文件名
*/
public void downloadFile(String downLoadPath, HttpServletRequest request,
HttpServletResponse response, String fileName) {
BufferedInputStream bis = null;
BufferedOutputStream bos = null;
try {
long fileLength = new File(downLoadPath).length();
/*
* response.setContentType("application/x-msdownload;");
* response.setHeader("Content-disposition", "attachment; filename="
* + fileName);
*/
String userAgent = request.getHeader("User-Agent");
// 针对IE或者以IE为内核的浏览器:
if (userAgent.contains("MSIE") || userAgent.contains("Trident")) {
fileName = URLEncoder.encode(fileName, "UTF-8");
} else {
// 非IE浏览器的处理:
fileName = new String(fileName.getBytes("UTF-8"), "ISO-8859-1");
}
response.setHeader("Content-disposition",
String.format("attachment; filename=\"%s\"", fileName));
response.setContentType("application/octet-stream;charset=utf-8");
response.setCharacterEncoding("UTF-8");
response.setHeader("Content-Length", String.valueOf(fileLength));
bis = new BufferedInputStream(new FileInputStream(downLoadPath));
bos = new BufferedOutputStream(response.getOutputStream());
byte[] buff = new byte[2048];
int bytesRead;
while (-1 != (bytesRead = bis.read(buff, 0, buff.length))) {
bos.write(buff, 0, bytesRead);
}
} catch (Exception e) {
e.printStackTrace();
} finally {
if (bis != null) {
try {
bis.close();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
if (bos != null) {
try {
bos.close();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
}
}
/**
* 下载文件
*
* @param downLoadPath
* 下载路径
* @param response
* @param fileName
* 文件名
*/
public void getFile(String downLoadPath, HttpServletRequest request,
HttpServletResponse response, String fileName) {
BufferedInputStream bis = null;
BufferedOutputStream bos = null;
try {
long fileLength = new File(downLoadPath).length();
String userAgent = request.getHeader("User-Agent");
// 针对IE或者以IE为内核的浏览器:
if (userAgent.contains("MSIE") || userAgent.contains("Trident")) {
fileName = URLEncoder.encode(fileName, "UTF-8");
} else {
// 非IE浏览器的处理:
fileName = new String(fileName.getBytes("UTF-8"), "ISO-8859-1");
}
response.setHeader("Content-disposition",
String.format("attachment; filename=\"%s\"", fileName));
response.setContentType("application/octet-stream;charset=utf-8");
response.setCharacterEncoding("UTF-8");
response.setHeader("Content-Length", String.valueOf(fileLength));
bis = new BufferedInputStream(new FileInputStream(downLoadPath));
bos = new BufferedOutputStream(response.getOutputStream());
byte[] buff = new byte[2048];
int bytesRead;
while (-1 != (bytesRead = bis.read(buff, 0, buff.length))) {
bos.write(buff, 0, bytesRead);
}
} catch (Exception e) {
e.printStackTrace();
} finally {
if (bis != null) {
try {
bis.close();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
if (bos != null) {
try {
bos.close();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
}
}
}