/**
* 文件上传
* @param request {@link HttpServletRequest}
* @param response {@link HttpServletResponse}
* @return json response
*/
@SuppressWarnings("unchecked")
@RequestMapping(value = "/fileUpload", method = RequestMethod.POST)
@ResponseBody
public void fileUpload(HttpServletRequest request,
HttpServletResponse response,
@RequestParam("imgFile") MultipartFile[] imgFile) {
try {
response.setCharacterEncoding("utf-8");
PrintWriter out = response.getWriter();
if(!ServletFileUpload.isMultipartContent(request)){
out.print(getError("请选择文件。"));
out.close();
return;
}
String dirName = request.getParameter("dir");
if (dirName == null) {
dirName = "image";
}
//定义允许上传的文件扩展名
Map<String, String> extMap = new HashMap<String, String>();
extMap.put("image", "gif,jpg,jpeg,png,bmp");
extMap.put("flash", "swf,flv");
extMap.put("media", "swf,flv,mp3,wav,wma,wmv,mid,avi,mpg,asf,rm,rmvb");
extMap.put("file", "doc,docx,xls,xlsx,ppt,htm,html,xml,txt,zip,rar,gz,bz2");
if(!extMap.containsKey(dirName)){
out.print(getError("目录名不正确。"));
out.close();
return;
}
// 保存文件
for(MultipartFile iFile : imgFile){
String fileName = iFile.getOriginalFilename();
//检查扩展名
String fileExt = fileName.substring(fileName.lastIndexOf(".") + 1).toLowerCase();
if(!Arrays.<String>asList(extMap.get(dirName).split(",")).contains(fileExt)){
out.print(getError("上传文件扩展名是不允许的扩展名。\n只允许" + extMap.get(dirName) + "格式。"));
out.close();
return;
}
SimpleDateFormat df = new SimpleDateFormat("yyyyMMddHHmmss");
String newFileName = df.format(new Date()) + "_" + new Random().nextInt(1000) + "." + fileExt;
JSONObject obj = new JSONObject();
try{
File uploadedFile = new File(Thread.currentThread().getContextClassLoader().getResource("/").getPath(), newFileName);
// 写入文件
FileUtils.copyInputStreamToFile(iFile.getInputStream(), uploadedFile);
String fileId = "http://h-guiyang.com/fastdfs/"+FastDFSClient.uploadFile(uploadedFile, "jpg");
obj.put("error", 0);
obj.put("url", fileId);
uploadedFile.delete();
}catch(Exception e){
e.printStackTrace();
out.print(getError("上传文件失败。"));
out.close();
return;
}
out.print(obj.toJSONString());
out.close();
}
} catch (Exception e) {
e.printStackTrace();
}
}
package net.hp.es.adm.healthcare.rphcp.application.portal.common.fastdfs;
import java.io.ByteArrayInputStream;
import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;
import java.io.InputStream;
import org.apache.commons.lang3.StringUtils;
import org.apache.log4j.Logger;
import net.hp.es.adm.healthcare.rphcp.application.portal.common.fastdfs.common.NameValuePair;
import net.hp.es.adm.healthcare.rphcp.application.portal.common.fastdfs.fastdfs.ClientGlobal;
import net.hp.es.adm.healthcare.rphcp.application.portal.common.fastdfs.fastdfs.StorageClient1;
import net.hp.es.adm.healthcare.rphcp.application.portal.common.fastdfs.fastdfs.StorageServer;
import net.hp.es.adm.healthcare.rphcp.application.portal.common.fastdfs.fastdfs.TrackerClient;
import net.hp.es.adm.healthcare.rphcp.application.portal.common.fastdfs.fastdfs.TrackerServer;
public class FastDFSClient {
//private static final String CONF_FILENAME = Thread.currentThread().getContextClassLoader().getResource("").getPath() + "fdfs_client.conf";
private static final String CONF_FILENAME = Thread.currentThread().getContextClassLoader().getResource("/").getPath() + "fdfs_client.conf";
private static StorageClient1 storageClient1 = null;
private static Logger logger = Logger.getLogger(FastDFSClient.class);
/**
* 只加载一次.
*/
static {
try {
logger.info("=== CONF_FILENAME:" + CONF_FILENAME);
ClientGlobal.init(CONF_FILENAME);
TrackerClient trackerClient = new TrackerClient(ClientGlobal.g_tracker_group);
TrackerServer trackerServer = trackerClient.getConnection();
if (trackerServer == null) {
logger.error("getConnection return null");
}
StorageServer storageServer = trackerClient.getStoreStorage(trackerServer);
if (storageServer == null) {
logger.error("getStoreStorage return null");
}
storageClient1 = new StorageClient1(trackerServer, storageServer);
} catch (Exception e) {
e.printStackTrace();
logger.error(e);
}
}
/**
*
* @param file
* 文件
* @param fileName
* 文件名
* @return 返回Null则为失败
*/
public static String uploadFile(File file, String fileext) {
FileInputStream fis = null;
try {
NameValuePair[] meta_list = null; // new NameValuePair[0];
fis = new FileInputStream(file);
byte[] file_buff = null;
if (fis != null) {
int len = fis.available();
file_buff = new byte[len];
fis.read(file_buff);
}
String fileid = storageClient1.upload_file1(file_buff, fileext, meta_list);
return fileid;
} catch (Exception ex) {
ex.printStackTrace();
logger.error(ex);
return null;
}finally{
if (fis != null){
try {
fis.close();
} catch (IOException e) {
logger.error(e);
}
}
}
}
/**
* 根据组名和远程文件名来删除一个文件
*
* @param groupName
* 例如 "group1" 如果不指定该值,默认为group1
* @param fileName
* 例如"M00/00/00/wKgxgk5HbLvfP86RAAAAChd9X1Y736.jpg"
* @return 0为成功,非0为失败,具体为错误代码
*/
public static int deleteFile(String groupName, String fileName) {
try {
int result = storageClient1.delete_file(groupName == null ? "group1" : groupName, fileName);
return result;
} catch (Exception ex) {
logger.error(ex);
return 0;
}
}
/**
* 根据fileId来删除一个文件(我们现在用的就是这样的方式,上传文件时直接将fileId保存在了数据库中)
*
* @param fileId
* file_id源码中的解释file_id the file id(including group name and filename);例如 group1/M00/00/00/ooYBAFM6MpmAHM91AAAEgdpiRC0012.xml
* @return 0为成功,非0为失败,具体为错误代码
*/
public static int deleteFile(String fileId) {
try {
int result = storageClient1.delete_file1(fileId);
return result;
} catch (Exception ex) {
logger.error(ex);
return 0;
}
}
/**
* 修改一个已经存在的文件
*
* @param oldFileId
* 原来旧文件的fileId, file_id源码中的解释file_id the file id(including group name and filename);例如 group1/M00/00/00/ooYBAFM6MpmAHM91AAAEgdpiRC0012.xml
* @param file
* 新文件
* @param filePath
* 新文件路径
* @return 返回空则为失败
*/
public static String modifyFile(String oldFileId, File file, String filePath) {
String fileid = null;
try {
// 先上传
fileid = uploadFile(file, filePath);
if (fileid == null) {
return null;
}
// 再删除
int delResult = deleteFile(oldFileId);
if (delResult != 0) {
return null;
}
} catch (Exception ex) {
logger.error(ex);
return null;
}
return fileid;
}
/**
* 文件下载
*
* @param fileId
* @return 返回一个流
*/
public static InputStream downloadFile(String fileId) {
try {
byte[] bytes = storageClient1.download_file1(fileId);
InputStream inputStream = new ByteArrayInputStream(bytes);
return inputStream;
} catch (Exception ex) {
logger.error(ex);
return null;
}
}
/**
* 获取文件后缀名(不带点).
*
* @return 如:"jpg" or "".
*/
private static String getFileExt(String fileName) {
if (StringUtils.isBlank(fileName) || !fileName.contains(".")) {
return "";
} else {
return fileName.substring(fileName.lastIndexOf(".") + 1); // 不带最后的点
}
}
}
var initModalFormEleValByReceiveRecordId = function(id){
$.ajax({
type : "GET",
async : false,// 同步请求
url : $.rphcp.getContextPath()+"/management/hcpr/articles/" + id + "/view",
dataType : "json",
success : function(data) {
debugger;
var article = data.datas;
$("#title").val(article.title);
$("#content").val(article.content);
itemAddEditor.html(article.content);
var type=article.articleType;
if (type=="原创") {
type=1;
}else if(type=="转载"){
type=2;
}else if(type=="翻译"){
type=3;
}
$("#articleType").val(type);//文章类型(1原创 2转载 3翻译)
var gree=article.degree;
$("#fication").val(article.fication);
$("#degree").val(gree);//亲密程度(1私密 2公开)
$("#receiveRecordModalReceiveRecordIdHiddenInput").val(article.id);
$("#createTime").val(article.createtime);//创建文章时间
$("#auditstatus").val(article.auditStatus);//卫计委审核状态
$("#artinstitution").val(article.artinstitution);//发布文章所属医院机构
$("#userId").val(article.userId);//创建人ID
$("#status").val(article.status);//文章状态
return false;
},
error : function() {
$.Toast.error("请求异常,查询文章信息失败!");
}
});
};
//获取模式窗口表单元素值
var getModalFormEleVal = function() {
debugger;
var postData = {};
itemAddEditor.sync();
postData.title=$.trim($("#title").val());//文章标题
var content=$.trim($("#content").val());//文章内容
postData.content=content;
postData.articleType=$.trim($("#articleType").val());//文章类型(1原创 2转载 3翻译)
postData.fication=$.trim($("#fication").val());//文章所属分类
postData.degree=$.trim($("#degree").val());//亲密程度(1.私密 2.公开)
//修改返回给后台的数据
postData.createtime=$.trim($("#createTime").val());//创建文章时间
postData.auditStatus=$.trim($("#auditstatus").val());//卫计委审核状态
postData.artinstitution=$.trim($("#artinstitution").val());//发布文章所属医院机构
postData.id=$.trim($("#receiveId").val());//创作文章ID
postData.userId=$.trim($("#userId").val());//创建人ID
postData.status=$.trim($("#status").val());//文章状态
return postData;
};
var getModelSuggestEleVal=function(){
debugger;
var postData = {};
postData.suggest=$.trim($("#suggest").val());//创作文章ID
return postData;
}
var cleanModalFormEleVal = function() {
$("#receiveRecordModalReceiveRecordIdHiddenInput").val("");
$("#receiveRecordModal form")[0].reset();// 重置表单
};
var getKindeditor=function(){
debugger;
editor = KindEditor.create('textarea[name="desc"]',{
resizeType : 1,
allowImageUpload:true,//允许上传图片
allowFileManager:true, //允许对上传图片进行管理
uploadJson:$.rphcp.getContextPath()+"/management/hcpr/articles/fileUpload",
items: ["source", "|", "undo", "redo", "|", "preview", "print", "template", "code",
"cut", "copy", "paste", "plainpaste", "wordpaste",
"|", "justifyleft", "justifycenter", "justifyright", "justifyfull", "insertorderedlist",
"insertunorderedlist", "indent", "outdent", "subscript", "superscript", "clearhtml", "quickformat",
"selectall", "|", "fullscreen", "/", "formatblock", "fontname", "fontsize", "|", "forecolor",
"hilitecolor", "bold", "italic", "underline", "strikethrough", "lineheight", "removeformat", "|", "image",
"flash", "media", "insertfile", "table", "hr", "emoticons", "baidumap", "pagebreak",
"anchor", "link", "unlink", "|", "about"],
/* fileManagerJson:$.rphcp.getContextPath()+'/management/hcpr/articles/fileManager',*/
afterChange:function(){this.sync();},
afterUpload: function(){this.sync();}, //图片上传后,将上传内容同步到textarea中
afterBlur: function(){this.sync();} 失去焦点时,将上传内容同步到textarea中
});
return editor;
};
loadSelect=function(selectedId){
$.ajax({
type : "GET",
async : false,// 同步请求
url : $.rphcp.getContextPath()+"/management/hcpr/articles/select",
dataType : "json",
success : function(data) {
debugger;
//1 创建select对象,将name属性指定
var select = $("#fication");
//2 添加提示选项
select.append($("<option value='' >---文章所属分类---</option>"));
$.each(data, function(i){
debugger;
// 每次遍历创建一个option对象
var $option = $("<option value='"+data[i].id+"' >"+data[i].name+"</option>");
if(data[i].id == selectedId){
//判断是否需要回显 ,如果需要使其被选中
$option.attr("selected","selected");
}
//并添加到select对象
select.append($option);
});
//5 将组装好的select对象放入页面指定位置
select.append(select);
return false;
},
error : function() {
$.Toast.error("请求异常,加载下拉选失败");
}
});
}