1.基本功能 1.基本功能
1.1.附件上传下载 1.1.附件上传下载
此案例主要展示附件的上传下载功能的相关效果及配置。允许上传的文件格式可在配置平台sys_uploader_strategy表中进行设置。
1.1.1.效果图展示
1.1.2.操作说明
新增表定义、业务对象具体可参考【表定义】、【新增业务对象】
1.2.文件上传配置 1.2.文件上传配置
1.2.1.界面是个上传控件效果,点击后弹出文件上传的选择框。
1.3.附件上传(表格内上传到ftp)1.3.附件上传(表格内上传到ftp)
实现表格上传到ftp。
1.4.附件上传(表单上传到ftp) 1.4.附件上传(表单上传到ftp)
通过自定义代码实现表单上传到ftp。
2.配置方法2.配置方法
2.1.附件上传下载2.1.附件上传下载
2.1.1.业务对象相关配置
2.1.1.1.在业务对象–管理页tab新增一笔数据,上传配置
2.1.1.2.在业务对象–方法定义tab中添加一笔数据,下载配置
2.1.1.3.提交,生成代码
2.1.2.项目配置
2.1.2.1.修改application.properties文件相关配置
2.2.文件上传配置2.2.文件上传配置
2.2.1.对象建模 –> 上传策略管理,点击【新增】按钮,新增一笔上传策略。
2.2.2.填写上传策略代码、组名称、文件大小限制、文件数量限制、大缩略图大小、小缩略图大小、BUCKET名称,选择文件类型限制、是否逻辑删除,填完后点击保存按钮。
2.2.3.对象建模 –> 业务对象管理,编辑要配置文件上传的业务对象,点击【可视化布局】按钮。
2.2.3.1.表单配置:选中要设置上传控件的ELEMENT,在右侧把控件类型更改为上传控件,或者直接从左侧工具箱的基础组件处拖拽。
2.2.3.2.表格配置:选中要设置上传控件列标题,在右侧把控件类型更改为上传控件。
2.2.4.设置完后点击保存,提交业务对象,并重新生成代码。
2.3.附件上传(表格内上传到ftp)2.3.附件上传(表格内上传到ftp)
配置
1.对象建模–业务对象–业务对象管理:业务对象在方法定义中配置三个自定义方法。
2.在生成的二次扩展js文件中编写自定义方法,具体代码可参考【3.1附件上传(表格内上传到ftp)】。
3.编辑业务对象,点击【可视化布局】按钮,在可视化界面将相关按钮配置出来,并把对应控件的控件类型改成【上传控件】。
4.修改配置文件:application.propertites
其中8086是tomcat的端口号,另外ftp的账户和密码需要有读写的权限
#updater service address
upload.fileAdd.url = http://localhost:8082/MyProject/attachment/uploadService
upload.fileAbolish.url = http://localhost:8082/MyProject/attachment/deleteService
upload.fileQuery.url = http://localhost:8082/MyProject/attachment/queryService
upload.file.sourceCode = CJ_IPF
upload.file.orgiId = 188
5.spring-security.xml文件新增这些配置
<!-- 文件上传-->
<http pattern="/attachment/uploadService" security="none"/>
<http pattern="/attachment/queryService" security="none"/>
<http pattern="/attachment/deleteService" security="none"/>
6.新增附件的实现类:具体代码参考【3.1附件上传(表格内上传到ftp)】。
7.数据库刷数据:
FS_UPLOADER_STRATEGY可以在该表中指定上传文件类型、限制文件上传大小,以及大图和小图的高度和宽度。
prompt Importing table FS_UPLOADER_STRATEGY…
set feedback off
set define off
insert into FS_UPLOADER_STRATEGY (ID, BUCKET_NAME, ALLOW_EXTENSIONS, SIZE_LIMIT, COUNT_LIMIT, IS_LOGIC_DELETE, LARGE_THUMBNAIL_SIZE, SMALL_THUMBNAIL_SIZE)
values (‘1’, ‘uploadFiles’, ‘jpg, png, gif, jpeg,doc, docx, txt’, 2000, 1, 0, ‘{\”width\”: 160, \”height\”: 160}’, ‘{\”width\”: 48, \”height\”: 48}’);
insert into FS_UPLOADER_STRATEGY (ID, BUCKET_NAME, ALLOW_EXTENSIONS, SIZE_LIMIT, COUNT_LIMIT, IS_LOGIC_DELETE, LARGE_THUMBNAIL_SIZE, SMALL_THUMBNAIL_SIZE)
values (‘2’, ‘uploadFiles’, ‘jpg, png, jpeg’, 2000, 1, 0, ‘{\”width\”: 80, \”height\”: 80}’, ‘{\”width\”: 30, \”height\”: 30}’);
insert into FS_UPLOADER_STRATEGY (ID, BUCKET_NAME, ALLOW_EXTENSIONS, SIZE_LIMIT, COUNT_LIMIT, IS_LOGIC_DELETE, LARGE_THUMBNAIL_SIZE, SMALL_THUMBNAIL_SIZE)
values (‘3’, ‘uploadFiles’, ‘jpg, png, gif, jpeg,doc, docx, txt’, 2000, 1, 0, ‘{\”width\”: 200, \”height\”: 100}’, ‘{\”width\”: 200, \”height\”: 100}’);
prompt Done.
代码
生成的html代码中,附件的表格上的代码
<g-upload-group key="1" ng-model="fileInfos" inital-show-count="1" disable-preview="false" show-deleter="never" auto-load-by-key="true" show-filename="false" upload-params="row" on-upload="onUploadTestExamAttachment3401(row,uploaderStrategy)" on-before-delete="onBeforeDeleteTestExamAttachment3401(row,uploaderStrategy)" />
3.常用扩展 3.常用扩展
3.1.附件上传(表格内上传到ftp)3.1.附件上传(表格内上传到ftp)
download方法【下载】
$scope.downloadTestExamAttachment3401 = function() {
var rows = $scope.testExamAttachment3401CheckedRows;
if (!rows || rows.length == 0) {
GillionMsg.alert(“提示”, “请选择一条记录”);
return;
}
var fileKey = rows[0].fileKey;
if (!fileKey || fileKey.length == 0) {
GillionMsg.alert(“提示”, “请先上传文件”);
return;
}
var iframeHtml = ‘ < iframe name = ”downloadFrame”id = ”‘ + fileKey + ‘”style = ”width: 0px;
height: 0px;” > </iframe>’;
$(iframeHtml).appendTo(‘body’);
$(“#” + fileKey).attr(“src”, $config.ctx + ‘/cloud / filesystem / downloadFileDef / ’ + fileKey + ’ ? fileType = BIG_THUMBNAIL’);
};
onUpload业务对象【上传】
$scope.onUploadTestExamAttachment3401 = function(row, uploaderStrategy) {
var name = row.fileInfos[0].name;
row.attachmentName = name.substring(0, name.lastIndexOf(“.”));
row.fileKey = row.fileInfos[0].fileKey;
row.isDeleted = ‘N’;
$scope.testExamAttachment3401Grid.finishEdit();
$scope.testExamAttachment3401Grid._reset();
if (row.rowStatus == 4) {
row.testExamAttachmentId = null;
// $scope.save();
$http.post($config.ctx + ‘ / testExamAttachment3401 / save’, row).success(function(data) {
if (data.success != undefined && data.success == true) {
for (var i in data.testExamAttachment3401) row[i] = data.testExamAttachment3401[i];
$scope.testExamAttachment3401Grid._reset();
}
});
} else {
row.rowStatus = 16
// $scope.update();
$http.post($config.ctx + ‘ / testExamAttachment3401 / update’, row).success(function(data) {
if (data.success != undefined && data.success == true) {
for (var i in data.testExamAttachment3401) row[i] = data.testExamAttachment3401[i];
$scope.testExamAttachment3401Grid._reset();
}
});
}
};
onBeforeDelete业务对象【上传删除】
$scope.onBeforeDeleteTestExamAttachment3401 = function(row, uploaderStrategy) {
var param = {};
param.testExamAttachmentId = row.testExamAttachmentId;
param.isLogic = false;
$scope.testExamAttachment3401Grid.finishEdit();
$scope.testExamAttachment3401Grid._reset();
$http.get($config.ctx + ‘ / testExamAttachment3401 / delete’, {
params: param
}).success(function(data) {
if (data.success != undefined && data.success == true) {
Arrays.remove($scope.testExamAttachment3401, row);
$scope.testExamAttachment3401Grid._reset();
}
});
};
类AttachmentServer代码
package com.gillion.platform.implement.classic.custom.web;
/*
import com.gillion.platform.framework.component.uploader.service.FileInfoService;*/
import com.gillion.platform.framework.component.uploader.utils.Config;
import com.gillion.platform.framework.core.query.Operation;
import com.gillion.platform.framework.core.web.BaseAbstractController;
import com.gillion.platform.utils.DateUtils;
import com.gillion.platform.utils.FtpUtil;
import com.gillion.platform.utils.ResponseUtils;
import com.gillion.platform.utils.StringUtils;
import com.gillion.upload.entity.FileInfo;
import com.gillion.upload.support.FileInfoService;
import net.coobird.thumbnailator.Thumbnails;
import net.coobird.thumbnailator.Thumbnails.Builder;
import org.apache.commons.io.IOUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.multipart.MultipartFile;
import java.io.*;
import java.util.*;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
/**
* Created by user on 16-8-3.
*/
@Controller
public class AttachmentServer extends BaseAbstractController {
private static Logger logger = LoggerFactory.getLogger(AttachmentServer.class);
protected static final String boName = "Attachment";
private static final String[] imgs = new String[] {
"BMP", "JPG", "JPEG", "PNG", "TIFF", "GIF", "PCX", "TGA", "EXIF",
"FPX", "SVG", "PSD", "CDR", "PCD", "DXF", "UFO", "EPS", "AI", "RAW"
};
private static final String _SMALL = "_small";
@Autowired
private FileInfoService fileInfoService;
//todo
@Autowired
// private TestExamAttachment3401Service testExamAttachment3401Service;
@Override
public String getBoName() {
return boName;
}
@RequestMapping(value = "attachment/deleteService", method = RequestMethod.POST)
public void deleteService(@RequestBody
FileInfo fileInfo, HttpServletRequest request, HttpServletResponse response)
throws Exception {
/* TestExamAttachment3401Example example = new TestExamAttachment3401Example();
example.and().andCreateCondition("FILE_KEY", Operation.EQ, fileInfo.getFileKey());
this.testExamAttachment3401Service.deleteByExample(example);*/
String fileName = fileInfo.getName();
String fileNameWithoutSubfix = fileName.substring(0,
fileName.lastIndexOf("."));
String subfix = fileName.substring(fileName.lastIndexOf("."));
String etag = fileInfo.getEtag();
if (StringUtils.isNotEmpty(etag)) {
fileName = fileNameWithoutSubfix + etag + subfix;
}
FtpUtil ftpUtil = new FtpUtil();
ftpUtil.connectFtp();
ftpUtil.startRemoveFile(fileInfo.getUrl(), fileName);
if (Arrays.asList(imgs).contains(subfix.substring(1).toUpperCase())) {
fileName = StringUtils.isEmpty(etag)
? (fileNameWithoutSubfix + _SMALL + subfix)
: (fileNameWithoutSubfix + etag + _SMALL + subfix);
ftpUtil.startRemoveFile(fileInfo.getUrl(), fileName);
}
ftpUtil.closeFtp();
}
private String getBaseFolder() {
return Config.getString("upload.fileDir");
}
private String getFilePath() {
String folder = getBaseFolder() + DateUtils.getCurrDateStr(1) + "/";
File fileDir = new File(folder);
if (!fileDir.exists()) {
fileDir.mkdirs();
}
return folder;
}
@RequestMapping(value = "attachment/uploadService", method = RequestMethod.POST)
public void uploadService(MultipartFile file, HttpServletRequest request,
HttpServletResponse response) throws Exception {
logger.error("开始上传附件");
// String uploadType = request.getParameter("file_uploadType");//附件类型
// String businessId = request.getParameter("file_businessId");//附件对应单据id
PrintWriter out = response.getWriter();
String fileName = file.getOriginalFilename();
String subfix = fileName.substring(fileName.lastIndexOf(".")); //后缀名
String fileNameWithoutSubfix = fileName.substring(0,
fileName.lastIndexOf(".")); //文件名
String uuid = UUID.randomUUID().toString().replace("-", "");
String uploadName = uuid + subfix;
FileOutputStream fos = null;
FtpUtil ftpUtil = new FtpUtil();
ftpUtil.connectFtp();
// FtpHelper fu = null;
/*try {
fu = new FtpHelper("172.16.10.100", 21, "public", "public");
fu.connectFTPServer();
InputStream inputStream = file.getInputStream();
String thumnailname = file.getOriginalFilename();
String filename = file.getName();
//创建目录,如果不存在就创建目录,如果存就反回false(表示目录已存在了
fu.getFtp().makeDirectory("/" + filename);
fu.uploadFile(inputStream,thumnailname,"/"+ filename);
logger.error("上传附件成功,附件名为:" + file.getOriginalFilename());
} catch (Exception e) {
System.out.println("异常信息:" + e.getMessage());
logger.error("上传附件失败:" + e.getMessage());
out.append(
"{\"message\":\"fail\", \"status\":false, \"fileKey\":\"[\\\"")
.append(uuid).append("\\\"]\"}");
} finally {
try {
fu.closeFTPClient();
} catch (Exception e) {
e.printStackTrace();
}
}*/
try {
// 上传文件到ftp服务器
String remoteDir = DateUtils.getCurrDateStr(1);
ftpUtil.startUploadFile(remoteDir, file.getInputStream(), uploadName);
// 上传缩略图
if (Arrays.asList(imgs).contains(subfix.substring(1).toUpperCase())) {
String smallImgFilePath = getFilePath() + uuid + _SMALL +
subfix;
Thumbnails.of(file.getInputStream()).size(50, 50)
.toFile(smallImgFilePath);
Builder<?extends InputStream> thumbnail = Thumbnails.of(file.getInputStream());
thumbnail.size(50, 50);
thumbnail.toFile(smallImgFilePath);
File smallImgFile = new File(smallImgFilePath);
ftpUtil.startUploadFile(remoteDir, smallImgFile);
smallImgFile.delete();
}
logger.error("上传附件成功,附件名为:" + file.getOriginalFilename());
} catch (IOException e) {
logger.error("上传附件失败:" + e.getMessage());
out.append(
"{\"message\":\"fail\", \"status\":false, \"fileKey\":\"[\\\"")
.append(uuid).append("\\\"]\"}");
return;
} finally {
try {
if (fos != null) {
fos.flush();
fos.close();
ftpUtil.closeFtp();
}
} catch (IOException e) {
logger.error(e.getMessage());
}
}
out.append(
"{\"message\":\"success\", \"status\":true, \"data\":\"[\\\"")
.append(uuid).append("\\\"]\"}");
}
@RequestMapping(value = "attachment/queryService", method = RequestMethod.POST)
public void queryService(@RequestBody
String requestBody, HttpServletResponse response) throws Exception {
PrintWriter out = response.getWriter();
out.append(
"{\"message\":\"success\", \"status\":true, data:[{\"file_path\":\"" +
DateUtils.getCurrDateStr(1) + "\"}]}");
}
@RequestMapping(value = "attachment/query", method = RequestMethod.POST)
public void queryAttachments(HttpServletRequest request,
HttpServletResponse response) throws Exception {
Map result = new HashMap();
/* Map<String, List> resultPhot = new LinkedHashMap<String, List>();
TestExamAttachment3401Example mdExample = TestExamAttachment3401Example.create();
List<TestExamAttachment3401> listMdAttachment = testExamAttachment3401Service
.selectByExample(mdExample);
Set<String> photoType = new HashSet<String>();
for (TestExamAttachment3401 mdAtt : listMdAttachment) {
List<List<FileInfo>> fileInfoS = new ArrayList<List<FileInfo>>();
if (StringUtils.isNotBlank(mdAtt.getFileKey())) {
FileInfo fileInfo = fileInfoService.findByFileKey(mdAtt
.getFileKey());
List<FileInfo> listFileInfo = new ArrayList<FileInfo>();
listFileInfo.add(fileInfo);
}
}*/
// result.put("resultPhot", resultPhot);
// result.put("listMdAttachment", listMdAttachment);
ResponseUtils.flushSuccess(response, "请求成功!", "result", result);
}
/**
* 获取附件模块类型
*
* @param attachment
* @param request
* @param response
* @throws Exception
*/
@RequestMapping(value = "attachment/queryAttachmentType", method = RequestMethod.POST)
public void queryAttachmentType(HttpServletRequest request,
HttpServletResponse response) throws Exception {
Map<String, String> result = new HashMap<String, String>();
Properties pro = new Properties();
pro.load(AttachmentServer.class.getResourceAsStream(
"/properties/attachment.properties"));
Enumeration enumeration = pro.propertyNames();
while (enumeration.hasMoreElements()) {
String key = (String) enumeration.nextElement();
result.put(key, pro.getProperty(key));
}
ResponseUtils.flushSuccess(response, "请求成功!", "result", result);
}
@RequestMapping(value = "attachment/downloadService")
public void downloadService(HttpServletRequest request,
HttpServletResponse response) throws Exception {
String fileKey = request.getParameter("fileKey");
if (StringUtils.isEmpty(fileKey)) {
throw new Exception("找不到上传文件,下载失败");
}
FileInfo fileInfo = fileInfoService.findByFileKey(fileKey);
if (fileInfo == null) {
throw new Exception("找不到上传文件,下载失败");
}
String name = fileInfo.getName();
String localBaseDir = getBaseFolder();
String subfix = name.substring(name.lastIndexOf("."));
String ftpFileName = null;
if (Arrays.asList(imgs)
.contains(name.substring(name.lastIndexOf("."))
.substring(1).toUpperCase())) {
ftpFileName = fileKey + subfix;
response.addHeader("Content-Length",
String.valueOf(fileInfo.getByteSize()));
} else {
ftpFileName = fileKey + subfix;
response.addHeader("Content-Length",
String.valueOf(fileInfo.getByteSize()));
}
try {
Thread.sleep(3000);
} catch (InterruptedException e) {
e.printStackTrace();
}
//临时目录
String[] subfixs = ftpFileName.split("\\.");
File file = File.createTempFile(subfixs[0], "." + subfixs[1]);
if (file != null) {
file.delete();
}
file = new File(file.getPath());
FtpUtil ftpUtil = new FtpUtil();
ftpUtil.connectFtp();
ftpUtil.startDownFile(localBaseDir, fileInfo.getUrl(), ftpFileName, file);
response.addHeader("Content-Disposition", "attachment;filename=" +
name);
response.addHeader("Content-Length",
String.valueOf(fileInfo.getByteSize()));
response.setContentType("application/octet-stream");
FileInputStream is = new FileInputStream(file);
try {
IOUtils.copy(is, response.getOutputStream());
} catch (Exception e) {
throw new Exception("下载失败");
} finally {
is.close();
file.delete();
ftpUtil.closeFtp();
}
}
/**
* 下载缩略图
*
* @param fileKey
* @param request
* @param response
* @throws Exception
*/
@RequestMapping(value = "cloud/filesystem/downloadFileDef/{fileKey}", method = RequestMethod.GET)
public void downloadFileDef(@PathVariable
String fileKey, HttpServletRequest request, HttpServletResponse response)
throws Exception {
String fileType = request.getParameter("fileType");
if (StringUtils.isEmpty(fileKey)) {
throw new Exception("找不到上传文件,下载失败");
}
FileInfo fileInfo = fileInfoService.findByFileKey(fileKey);
if (fileInfo == null) {
throw new Exception("找不到上传文件,下载失败");
}
String name = fileInfo.getName();
String fileNameWithoutSubfix = name.substring(0, name.lastIndexOf("."));
String subfix = name.substring(name.lastIndexOf("."));
String etag = fileInfo.getEtag();
String ftpFileName = null;
if (Arrays.asList(imgs)
.contains(name.substring(name.lastIndexOf("."))
.substring(1).toUpperCase())) {
ftpFileName = fileKey + subfix;
response.addHeader("Content-Length",
String.valueOf(fileInfo.getByteSize()));
// if ("BIG_THUMBNAIL".equals(fileType)) {
// /*ftpFileName = StringUtils.isEmpty(etag) ? name
// : (fileNameWithoutSubfix + etag + subfix);*/
// ftpFileName=fileKey+subfix;
// response.addHeader("Content-Length",
// String.valueOf(fileInfo.getByteSize()));
// } else
// /*ftpFileName = StringUtils.isEmpty(etag) ? (fileNameWithoutSubfix
// + _SMALL + subfix) : (fileNameWithoutSubfix + etag
// + _SMALL + subfix);*/
// ftpFileName=fileKey+_SMALL+subfix;
} else {
/*ftpFileName = StringUtils.isEmpty(etag) ? name : (fileNameWithoutSubfix
+ etag + subfix);*/
ftpFileName = fileKey + subfix;
response.addHeader("Content-Length",
String.valueOf(fileInfo.getByteSize()));
}
try {
Thread.sleep(3000);
} catch (InterruptedException e) {
e.printStackTrace();
}
//临时目录
String[] subfixs = ftpFileName.split("\\.");
File file = File.createTempFile(subfixs[0], "." + subfixs[1]);
if (file != null) {
file.delete();
}
file = new File(file.getPath());
String localBaseDir = getBaseFolder();
FtpUtil ftpUtil = new FtpUtil();
ftpUtil.connectFtp();
ftpUtil.startDownFile(localBaseDir, fileInfo.getUrl(), ftpFileName, file);
//File file = new File(localBaseDir + File.separator + ftpFileName);
response.addHeader("Content-Disposition",
"attachment;filename=" +
(new String(name.getBytes("UTF-8"), "ISO-8859-1")));
response.setContentType("application/octet-stream");
InputStream is = new FileInputStream(file);
try {
IOUtils.copy(is, response.getOutputStream());
} catch (Exception e) {
throw new Exception("下载失败");
} finally {
is.close();
file.delete();
ftpUtil.closeFtp();
}
}
}
类AttachmentUploadController
package com.gillion.platform.implement.classic.custom.web;
import com.gillion.platform.bizrule.core.service.RuleService;
import com.gillion.platform.framework.core.web.BaseAbstractController;
import com.gillion.sample.test.service.TestExamAttachment3401Service;
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.jdbc.core.JdbcTemplate;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.servlet.ModelAndView;
import java.io.IOException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
/**
* <pre>
* 附件管理缩写MDAT(MdAttachment)控制器类
* </pre>
*
* <br>
* JDK版本:1.5
*
* @author chenql
* @version 1.0
* @see The author for more details
* @since 1.0
*/
@Controller
public class AttachmentUploadController extends BaseAbstractController {
protected static final String boName = "MdAttachment";
/** the filed log */
protected Log log = LogFactory.getLog(this.getClass());
@Autowired
protected RuleService ruleService;
@Autowired
protected JdbcTemplate jdbcTemplate;
/* (non-Javadoc)
* @see com.gillion.framework.core.web.BaseAbstractController#getBoName()
*/
@Override
public String getBoName() {
return boName;
}
public void setRuleService(RuleService ruleService) {
this.ruleService = ruleService;
}
public void setJdbcTemplate(JdbcTemplate jdbcTemplate) {
this.jdbcTemplate = jdbcTemplate;
}
/**
* 批量保存
*
* @param idStr
* @return
* @throws Exception
* @
*/
@RequestMapping(value = "cloud/filesystem/uploadFile/{fileKey}", method = RequestMethod.GET)
public ModelAndView uploadFile(@PathVariable
String fileKey, HttpServletRequest request, HttpServletResponse response)
throws IOException {
return new ModelAndView("redirect:/cloud/filesystem/downloadFileDef/" +
fileKey);
}
}
类Ftp
package com.gillion.platform.utils;
public class Ftp {
private String ipAddr; // ip地址
private Integer port; // 端口号
private String userName; // 用户名
private String pwd; // 密码
private String path; // 路径
public String getIpAddr() {
return ipAddr;
}
public void setIpAddr(String ipAddr) {
this.ipAddr = ipAddr;
}
public Integer getPort() {
return port;
}
public void setPort(Integer port) {
this.port = port;
}
public String getUserName() {
return userName;
}
public void setUserName(String userName) {
this.userName = userName;
}
public String getPwd() {
return pwd;
}
public void setPwd(String pwd) {
this.pwd = pwd;
}
public String getPath() {
return path;
}
public void setPath(String path) {
this.path = path;
}
}
类FtpUtil
package com.gillion.platform.utils;
import com.gfa4j.util.StringUtils;
import com.gillion.platform.framework.component.uploader.utils.Config;
import org.apache.commons.net.ftp.FTPClient;
import org.apache.commons.net.ftp.FTPFile;
import org.apache.commons.net.ftp.FTPReply;
import org.apache.log4j.Logger;
import java.io.*;
import java.text.DateFormat;
import java.text.SimpleDateFormat;
import java.util.Calendar;
public class FtpUtil {
private static Logger logger = Logger.getLogger(FtpUtil.class);
private static final String GBK = "GBK";
private static final String ISO_8859_1 = "iso-8859-1";
private static final Integer DEFAULT_PORT = 21;
private static Ftp ftp = new Ftp();
static {
ftp.setIpAddr(Config.getString("ftp.host"));
ftp.setUserName(Config.getString("ftp.userName"));
ftp.setPwd(Config.getString("ftp.pwd"));
ftp.setPath(Config.getString("ftp.basePath"));
int port = DEFAULT_PORT;
try {
port = Integer.parseInt(Config.getString("ftp.port"));
} catch (Exception e) {
port = DEFAULT_PORT;
logger.info("ftp配置没有设置端口号");
}
ftp.setPort(port);
}
private FTPClient ftpClient;
/**
* @param args
* @throws Exception
*/
public static void main(String[] args) throws Exception {
DateFormat dateFmt = new SimpleDateFormat("yyyyMMdd");
String strToday = dateFmt.format(Calendar.getInstance().getTime());
File file = new File("d:/ftp_test.txt");
FtpUtil ftpUtil = new FtpUtil();
ftpUtil.startUploadFile(strToday, file);
}
/**
* 获取ftp连接
*
* @param f
* @return
* @throws Exception
*/
public boolean connectFtp() throws Exception {
ftpClient = new FTPClient();
boolean flag = false;
int reply;
if (ftp.getPort() == null) {
ftpClient.connect(ftp.getIpAddr(), DEFAULT_PORT);
} else {
ftpClient.connect(ftp.getIpAddr(), ftp.getPort());
}
ftpClient.login(ftp.getUserName(), ftp.getPwd());
ftpClient.setFileType(FTPClient.BINARY_FILE_TYPE);
ftpClient.enterLocalPassiveMode();
reply = ftpClient.getReplyCode();
if (!FTPReply.isPositiveCompletion(reply)) {
logger.error(" FTP连接失败");
ftpClient.disconnect();
return flag;
}
ftpClient.changeWorkingDirectory(ftp.getPath());
flag = true;
return flag;
}
/**
* 关闭ftp连接
*/
public void closeFtp() {
if ((ftpClient != null) && ftpClient.isConnected()) {
try {
ftpClient.logout();
ftpClient.disconnect();
} catch (IOException e) {
e.printStackTrace();
}
}
}
private String getUploadDir(Ftp ftp, String remoteDir)
throws Exception {
String newDir = ftp.getPath();
if (StringUtils.isNotEmpty(remoteDir)) {
newDir += ("/" + remoteDir);
}
String[] dirs = newDir.split("/");
String curDir = "";
for (String dir : dirs) {
if ("/".equals(curDir)) {
curDir += dir;
} else {
curDir += ("/" + dir);
}
if (!ftpClient.changeWorkingDirectory(curDir)) {
ftpClient.makeDirectory(curDir);
}
}
return newDir;
}
/**
* 执行上传文件,到指定目录
*
* @param remoteDir ftp存放目录
* @param file 文件内容
* @throws Exception 上传错误信息
*/
public void startUploadFile(String remoteDir, File file)
throws Exception {
FileInputStream fis = new FileInputStream(file);
ftpClient.changeWorkingDirectory(getUploadDir(ftp, remoteDir));
ftpClient.storeFile(new String(file.getName().getBytes(GBK), ISO_8859_1),
fis);
fis.close();
}
/**
* 上传文件到ftp服务器
*
* @param remoteDir ftp文件存放目录
* @param inputStream 文件信息
* @param fileName 文件名
* @throws Exception 上传异常信息
*/
public void startUploadFile(String remoteDir, InputStream inputStream,
String fileName) throws Exception {
ftpClient.changeWorkingDirectory(getUploadDir(ftp, remoteDir));
String replyCode = ftpClient.getReplyString();
ftpClient.storeFile(new String(fileName.getBytes(GBK), ISO_8859_1),
inputStream);
inputStream.close();
}
/**
* 执行上传二进制流,到指定目录
*
* @param bytes 文件内容
* @param remoteDir ftp存放目录
* @param fileName 文件名
* @throws Exception 上传错误信息
*/
public void startUploadFile(byte[] bytes, String remoteDir, String fileName)
throws Exception {
String newDir = getUploadDir(ftp, remoteDir);
ftpClient.changeWorkingDirectory(newDir);
InputStream inputStream = new ByteArrayInputStream(bytes);
ftpClient.storeFile(fileName, inputStream);
inputStream.close();
}
/**
* 下载链接配置,整个文件夹下载到本地
*
* @param localBaseDir 本地目录
* @param remoteBaseDir 远程目录
* @throws Exception
*/
public void startDownDir(String localBaseDir, String remoteBaseDir)
throws Exception {
startDownFiles(localBaseDir, remoteBaseDir, null);
}
/**
* 下载链接配置,下载文件到本地
*
* @param localBaseDir 本地目录
* @param remoteBaseDir 远程目录
* @param filenames filenames为空默认下载整个文件夹包括子文件夹,filenames不为空下载多个文件
* @throws Exception
*/
public void startDownFile(String localBaseDir, String remoteBaseDir,
String filename, File file) throws Exception {
try {
boolean changedir = ftpClient.changeWorkingDirectory(ftp.getPath() +
"/" + remoteBaseDir);
if (changedir) {
OutputStream outputStream = new FileOutputStream(file);
ftpClient.retrieveFile(new String(filename.getBytes(GBK),
ISO_8859_1), outputStream);
outputStream.flush();
outputStream.close();
}
} catch (Exception e) {
logger.error("下载过程中出现异常", e);
}
}
/**
* 下载链接配置,下载文件到本地
*
* @param localBaseDir 本地目录
* @param remoteBaseDir 远程目录
* @param filenames filenames为空默认下载整个文件夹包括子文件夹,filenames不为空下载多个文件
* @throws Exception
*/
public void startDownFiles(String localBaseDir, String remoteBaseDir,
String[] filenames) throws Exception {
try {
boolean changedir = ftpClient.changeWorkingDirectory(remoteBaseDir);
if (changedir) {
FTPFile[] files = null;
files = ftpClient.listFiles();
for (int i = 0; i < files.length; i++) {
if (!files[i].getName().equals(".") &&
!files[i].getName().equals("..")) {
if ((filenames == null) || (filenames.length == 0)) {
// filenames为空默认下载整个文件夹包括子文件夹
downloadFile(files[i], localBaseDir, remoteBaseDir);
} else {
// filenames不为空下载多个文件
if (files[i].isFile()) {
for (int j = 0; j < filenames.length; j++) {
if (files[i].getName().equals(filenames[j])) {
downloadFile(files[i], localBaseDir,
remoteBaseDir);
} else {
logger.error("文件" + filenames[j] +
"不存在");
}
}
}
}
}
}
}
} catch (Exception e) {
logger.error("下载过程中出现异常", e);
}
}
/**
* 下载FTP文件 当你需要下载FTP文件的时候,调用此方法 根据<b>获取的文件名,本地地址,远程地址</b>进行下载
*
* @param ftpFile
* @param relativeLocalPath
* @param relativeRemotePath
*/
private void downloadFile(FTPFile ftpFile, String relativeLocalPath,
String relativeRemotePath) {
if (ftpFile.isFile()) {
if (ftpFile.getName().indexOf("?") == -1) {
OutputStream outputStream = null;
try {
File locaFile = new File(relativeLocalPath +
ftpFile.getName());
// 判断文件是否存在,存在则返回
if (locaFile.exists()) {
return;
} else {
outputStream = new FileOutputStream(relativeLocalPath +
ftpFile.getName());
ftpClient.retrieveFile(new String(
ftpFile.getName().getBytes(GBK), ISO_8859_1),
outputStream);
outputStream.flush();
outputStream.close();
}
} catch (Exception e) {
logger.error(e);
} finally {
try {
if (outputStream != null) {
outputStream.close();
}
} catch (IOException e) {
logger.error("输出文件流异常");
}
}
}
} else {
String newlocalRelatePath = relativeLocalPath + ftpFile.getName();
String newRemote = new String(relativeRemotePath +
ftpFile.getName().toString());
File fl = new File(newlocalRelatePath);
if (!fl.exists()) {
fl.mkdirs();
}
try {
newlocalRelatePath = newlocalRelatePath + '/';
newRemote = newRemote + "/";
String currentWorkDir = ftpFile.getName().toString();
boolean changedir = ftpClient.changeWorkingDirectory(currentWorkDir);
if (changedir) {
FTPFile[] files = null;
files = ftpClient.listFiles();
for (int i = 0; i < files.length; i++) {
if (!files[i].getName().equals(".") &&
!files[i].getName().equals("..")) {
downloadFile(files[i], newlocalRelatePath, newRemote);
}
}
}
if (changedir) {
ftpClient.changeToParentDirectory();
}
} catch (Exception e) {
logger.error(e);
}
}
}
/**
* 下载FTP文件 二进制流传输
*
* @param relativeRemotePath
*/
public byte[] startDownloadFileByte(String relativeRemotePath,
String filename) throws Exception {
try {
boolean changedir = ftpClient.changeWorkingDirectory(relativeRemotePath);
if (changedir) {
// 读取图片字节数组
ftpClient.enterLocalPassiveMode();
InputStream in = ftpClient.retrieveFileStream(new String(
filename.getBytes(GBK), ISO_8859_1));
byte[] data = new byte[in.available()];
in.read(data);
in.close();
return data;
}
} catch (Exception e) {
logger.error("下载过程中出现异常", e);
}
return null;
}
/**
* <p>
* 删除ftp上的文件
* </p>
*
* @param pathname 路径
* @return true || false
*/
private boolean removeFile(String pathname) {
boolean flag = false;
if (ftpClient != null) {
try {
FTPFile[] files = ftpClient.listFiles(pathname);
for (FTPFile ftpFile : files) {
String fileName = ftpFile.getName();
if (!fileName.equals(".") && !fileName.equals("..")) {
if (ftpFile.isDirectory()) {
removeFile(pathname + "/" +
new String(fileName.getBytes(GBK), ISO_8859_1));
}
if (ftpFile.isFile()) {
ftpClient.deleteFile(pathname + "/" +
new String(fileName.getBytes(GBK), ISO_8859_1));
}
}
}
flag = ftpClient.removeDirectory(pathname);
} catch (IOException e) {
e.printStackTrace();
return flag;
}
}
return flag;
}
/**
* <p>
* 删除ftp上的文件,单个文件
* </p>
*
* @param pathname 路径
* @return true || false
*/
public void startRemoveFile(String pathname, String filename)
throws Exception {
startRemoveFiles(pathname, new String[] { filename });
}
/**
* <p>
* 删除ftp上的文件,多个文件
* </p>
*
* @param pathname 路径
* @return true || false
*/
public void startRemoveFiles(String pathname, String[] filename)
throws Exception {
if (ftpClient != null) {
try {
for (int i = 0; i < filename.length; i++) {
ftpClient.deleteFile(pathname + "/" +
new String(filename[i].getBytes(GBK), ISO_8859_1));
}
} catch (IOException e) {
e.printStackTrace();
}
}
}
/**
* 批量删除ftp上的文件
*
* @param srcFname
* @return
*/
public void removeFiles(String[] srcFname) {
for (String file : srcFname) {
removeFile(file);
}
}
/**
* 删除时候调此方法
*
* @param srcFname 要删除的文件 EXP:"/aaa";
* @throws Exception
*/
public void deleteFileEn(String srcFname) throws Exception {
connectFtp();
removeFile(srcFname);
closeFtp();
}
/**
* 批量删除调用此方法
*
* @param srcFname 要删除的文件数组{"aaa","bbb"}
* @throws Exception
*/
public void deleteFilesEn(String[] srcFname) throws Exception {
connectFtp();
removeFiles(srcFname);
closeFtp();
}
}
3.2.附件上传(表单上传到ftp) 3.2.附件上传(表单上传到ftp)
前端代码
1.在前端HTML增加界面上写一个g-upload-group
标签,代码如下:
<g-upload-group key="“2”" initial-show-count="“1”" disable-preview="“true”" show-deleter="“always”" ng-model="“licenseFile”" show-filename="“true”" on-upload="“onUploadLicense(row,uploaderStrategy)”" on-before-delete="“onBeforeDeleteLicense(row,uploaderStrategy)”" />
</body>
2.在js中配置on-upload方法和on-before-delete方法,on-upload方法用于上传完回调参数到前台界面,一般用于改变实体状态,具体代码如下:
$scope.onUploadLicense = function(row, uploaderStrategy) {
console.log(“ === =============updape”);
console.log($scope.licenseFile);
if ($scope.licenseFile.length == 1) {
$scope.sysRegister.companyLicense = $scope.licenseFile[0].fileKey;
if ($scope.sysRegister.rowStatus == 2) {
$scope.sysRegister.rowStatus = 16;
}
$scope._pageState.setDataStateModify();
}
}
3.on-before-delete方法用于删除前调用的方法,一般用于改变实体状态
$scope.onBeforeDeleteLicense = function(row, uploaderStrategy) {
$scope.sysRegister.companyLicense = ”;
$scope._pageState.setDataStateModify();
if ($scope.sysRegister.rowStatus == 2) {
$scope.sysRegister.rowStatus = 16;
}
$scope.licenseFile = [];
return true;
}
后端控制器代码
1.在com.gillion.online.sys.upload.web新增一个上传方法控制器AttachmentServer.java,具体代码可见【3.1】。
2.后端工具类代码如下:
在com.gillion.util.ftp增加用于上传到ftp调用到的类Ftp.java和FtpUtil.java,具体代码可见【3.1】。
3.application.properties增加配置文件
1)updater service addresss说明8081本地端口号本地上下文
upload.fileAdd.url = http://localhost:8081/t/attachment/uploadService
upload.fileAbolish.url = http://localhost:8081/t/attachment/deleteService
upload.fileQuery.url = http://localhost:8081/t/attachment/queryServiceupload.file.sourceCode = CJ_IPFupload.file.orgiId = 188
2)ftp文件地址
ftp.host=xxx.xxx.xxx.xx
ftp.port=xx
ftp.visitPort=xx
ftp.userName=admin
ftp.pwd=admin
ftp.basePath=/
用于后台调用第三点配置的AttachmentServer.java中的方法。
4.上传方法不受权限控制配置:如果为了防止上传方法是在不需要登录的页面下调用,则需要在spring-security-extend.java中增加几个权限
<!– ####################### 资源权限白名单配置 ####################### –>
<http pattern=”/attachment/queryService” security=”none”/>
<http pattern=”/attachment/deleteService” security=”none”/>
<http pattern=”/attachment/queryAttachmentType” security=”none”/>
<http pattern=”/attachment/downloadService” security=”none”/>
<http pattern=”/cloud/filesystem/downloadFileDef/{fileKey}” security=”none”/>