公司项目用到AngularJS,做批量文件上传,研究了一下,准备用angular-file-upload插件来实现,由于AngularJS也是刚刚接触,很多东西不熟,查阅了大量博客、文档,修改了例子中的错误,最后实现了效果,记录一下,为新手填些坑。
查考博客:
http://bbs.csdn.net/topics/392037244
http://blog.csdn.net/w410589502/article/details/53906145
http://www.cnblogs.com/chenfei0801/p/3427310.html
1:导入js包
angular-file-upload.min.js
2:配置
Spring-mvc.xml
<beanid="multipartResolver"class="org.springframework.web.multipart.commons.CommonsMultipartResolver">
<propertyname="maxUploadSize"value="1048576"/>
</bean>
3:maven依赖
<dependency>
<groupId>commons-net</groupId>
<artifactId>commons-net</artifactId>
<version>3.3</version>
</dependency>
<dependency>
<groupId>commons-io</groupId>
<artifactId>commons-io</artifactId>
<version>2.2</version>
</dependency>
4:页面
多选
<inputtype="file"nv-file-select=""uploader="uploader"multiple /><br/>
单选
<input type="file" nv-file-select=""uploader="uploader"/>
<buttontype="button"class="btnbtn-success btn-s"ng-click="uploader.uploadAll()"ng-disabled="!uploader.getNotUploadedItems().length">
<spanclass="glyphiconglyphicon-upload"></span>
全部上传
</button>
5:js(controller)
'use strict'; angular .module('app', ['angularFileUpload']) .controller('AppController', ['$scope','FileUploader', function($scope, FileUploader) { var uploader = $scope.uploader =new FileUploader({ url:'upload.do', method: 'POST', //带入值 formData :[{test:1}]
});
// FILTERS
uploader.filters.push({ name: 'customFilter', fn: function(item/*{File|FileLikeObject}*/, options) { returnthis.queue.length < 10; } });
// CALLBACKS
uploader.onWhenAddingFileFailed = function(item/*{File|FileLikeObject}*/, filter, options) { console.info('onWhenAddingFileFailed', item, filter, options); }; uploader.onAfterAddingFile = function(fileItem) { console.info('onAfterAddingFile', fileItem); }; uploader.onAfterAddingAll = function(addedFileItems) { console.info('onAfterAddingAll', addedFileItems); }; uploader.onBeforeUploadItem = function(item) {
console.info('onBeforeUploadItem', item); }; uploader.onProgressItem = function(fileItem, progress) { console.info('onProgressItem', fileItem, progress); }; uploader.onProgressAll = function(progress) { console.info('onProgressAll', progress); }; uploader.onSuccessItem = function(fileItem, response, status, headers) { console.info('onSuccessItem', fileItem, response, status, headers); }; uploader.onErrorItem = function(fileItem, response, status, headers) { console.info('onErrorItem', fileItem, response, status, headers); }; uploader.onCancelItem = function(fileItem, response, status, headers) { console.info('onCancelItem', fileItem, response, status, headers); }; uploader.onCompleteItem = function(fileItem, response, status, headers) { console.info('onCompleteItem', fileItem, response, status, headers); }; uploader.onCompleteAll = function() { console.info('onCompleteAll'); };
console.info('uploader', uploader); }]);
|
6:java
@Controller public class UploadController { Log LOG = LogFactory.getLog(SysParamMgrController.class); @RequestMapping(value="/upload.do", method = RequestMethod.POST) public @ResponseBody void editItemsSubmitJSON(HttpServletRequestrequest, @RequestParam("file") MultipartFilefile,MultipartHttpServletRequest MultiRequest) throws Exception { try { //带入数据预留点 DefaultMultipartHttpServletRequest defaultRequest = (DefaultMultipartHttpServletRequest) MultiRequest; MultiValueMap fileMap =defaultRequest.getMultiFileMap(); Map<String, String[]> params =defaultRequest.getParameterMap(); if (params.size() > 0) { String[] str =params.get("test"); if (str.length > 0) System.out.println(str[0]); } // 原始名称 String originalFilename = file.getOriginalFilename(); // 上传文件 if (file !=null && originalFilename != null && originalFilename.length() > 0) { //上传至FTP //项目本地文件存放路径 String basePath ="/test"; String uploadFileName =file.getOriginalFilename(); String fileStoredPath = "/upload/";
if (StringUtils.isNotBlank(uploadFileName)) { //截取文件格式名 String suffix =uploadFileName.substring(uploadFileName.indexOf(".")); //重新拼装文件名 (可修改文件名预留) String newFileName =originalFilename; String savePath =basePath+ "/" +newFileName; File saveFile =new File(savePath); File parentFile =saveFile.getParentFile(); Boolean a=saveFile.exists(); if (saveFile.exists()) { saveFile.delete(); } else { if (!parentFile.exists()) { parentFile.mkdirs(); } } //复制文件到指定路径 FileUtils.copyInputStreamToFile(file.getInputStream(),saveFile); //上传文件到服务器 String b=saveFile.getName(); FTPClientUtil.upload(saveFile,fileStoredPath);
} } } catch (Exceptionex) { System.out.println(ex.getMessage()); } }
} |
7 ftp上传工具类
package com.xunfang.tools;
import java.io.File; import java.io.FileInputStream; import java.io.FileOutputStream; import java.io.IOException; import java.io.InputStream; import java.io.OutputStream; import java.net.SocketException; import java.util.HashMap; import java.util.Map; import java.util.Properties;
import org.apache.commons.lang.StringUtils; import org.apache.commons.net.ftp.FTP; import org.apache.commons.net.ftp.FTPClient; import org.apache.commons.net.ftp.FTPReply; import org.slf4j.Logger; import org.slf4j.LoggerFactory;
/** * FTP客户端工具 */ public class FTPClientUtil {
/** * 日志 */ private static final Logger LOGGER = LoggerFactory.getLogger(FTPClientUtil.class);
/** * FTP server configuration--IP key,value is type of String */ public static final String SERVER_IP = "SERVER_IP";
/** * FTP server configuration--Port key,value is type of Integer */ public static final String SERVER_PORT = "SERVER_PORT";
/** * FTP server configuration--ANONYMOUS Log in key, value is type of Boolean */ public static final String IS_ANONYMOUS = "IS_ANONYMOUS";
/** * user name of anonymous log in */ public static final String ANONYMOUS_USER_NAME = "anonymous";
/** * password of anonymous log in */ public static final String ANONYMOUS_PASSWORD = "";
/** * FTP server configuration--log in user name, value is type of String */ public static final String USER_NAME = "USER_NAME";
/** * FTP server configuration--log in password, value is type of String */ public static final String PASSWORD = "PASSWORD";
/** * FTP server configuration--PASV key, value is type of Boolean */ public static final String IS_PASV = "IS_PASV";
/** 本地字符编码 */ private static String LOCAL_CHARSET = "GBK";
// FTP协议里面,规定文件名编码为iso-8859-1 private static String SERVER_CHARSET = "ISO-8859-1";
/** * FTP server configuration--working directory key, value is type of String While logging in, the current directory * is the user's home directory, the workingDirectory must be set based on it. Besides, the workingDirectory must * exist, it can not be created automatically. If not exist, file will be uploaded in the user's home directory. If * not assigned, "/" is used. */ public static final String WORKING_DIRECTORY = "WORKING_DIRECTORY";
public static Map<String, Object> serverCfg = new HashMap<String, Object>();
static Properties prop;
static{ LOGGER.info("开始加载ftp.properties文件!"); prop = new Properties(); try { InputStream fps = FTPClientUtil.class.getResourceAsStream("/ftp.properties"); prop.load(fps); fps.close(); } catch (Exception e) { LOGGER.error("读取ftp.properties文件异常!",e); } serverCfg.put(FTPClientUtil.SERVER_IP, values("SERVER_IP")); serverCfg.put(FTPClientUtil.SERVER_PORT, Integer.parseInt(values("SERVER_PORT"))); serverCfg.put(FTPClientUtil.USER_NAME, values("USER_NAME")); serverCfg.put(FTPClientUtil.PASSWORD, values("PASSWORD")); LOGGER.info(String.valueOf(serverCfg)); }
/** * Upload a file to FTP server. * * @param serverCfg : FTP server configuration * @param filePathToUpload : path of the file to upload * @param fileStoredName : the name to give the remote stored file, null, "" and other blank word will be replaced * by the file name to upload * @throws IOException * @throws SocketException */ public static final void upload(Map<String, Object> serverCfg, String filePathToUpload, String fileStoredName) throws SocketException, IOException { upload(serverCfg, new File(filePathToUpload), fileStoredName); }
/** * Upload a file to FTP server. * * @param serverCfg : FTP server configuration * @param fileToUpload : file to upload * @param fileStoredName : the name to give the remote stored file, null, "" and other blank word will be replaced * by the file name to upload * @throws IOException * @throws SocketException */ public static final void upload(Map<String, Object> serverCfg, File fileToUpload, String fileStoredName) throws SocketException, IOException { if (!fileToUpload.exists()) { throw new IllegalArgumentException("File to upload does not exists:" + fileToUpload.getAbsolutePath
()); } if (!fileToUpload.isFile()) { throw new IllegalArgumentException("File to upload is not a file:" + fileToUpload.getAbsolutePath()); } if (StringUtils.isBlank((String) serverCfg.get(SERVER_IP))) { throw new IllegalArgumentException("SERVER_IP must be contained in the FTP server configuration."); } transferFile(true, serverCfg, fileToUpload, fileStoredName, null, null); }
/** * Download a file from FTP server * * @param serverCfg : FTP server configuration * @param fileNameToDownload : file name to be downloaded * @param fileStoredPath : stored path of the downloaded file in local * @throws SocketException * @throws IOException */ public static final void download(Map<String, Object> serverCfg, String fileNameToDownload, String fileStoredPath) throws SocketException, IOException { if (StringUtils.isBlank(fileNameToDownload)) { throw new IllegalArgumentException("File name to be downloaded can not be blank."); } if (StringUtils.isBlank(fileStoredPath)) { throw new IllegalArgumentException("Stored path of the downloaded file in local can not be blank."); } if (StringUtils.isBlank((String) serverCfg.get(SERVER_IP))) { throw new IllegalArgumentException("SERVER_IP must be contained in the FTP server configuration."); } transferFile(false, serverCfg, null, null, fileNameToDownload, fileStoredPath); }
private static final void transferFile(boolean isUpload, Map<String, Object> serverCfg, File fileToUpload, String serverFileStoredName, String fileNameToDownload, String localFileStoredPath) throws
SocketException, IOException { String host = (String) serverCfg.get(SERVER_IP); Integer port = (Integer) serverCfg.get(SERVER_PORT); Boolean isAnonymous = (Boolean) serverCfg.get(IS_ANONYMOUS); String username = (String) serverCfg.get(USER_NAME); String password = (String) serverCfg.get(PASSWORD); Boolean isPASV = (Boolean) serverCfg.get(IS_PASV); String workingDirectory = (String) serverCfg.get(WORKING_DIRECTORY); FTPClient ftpClient = new FTPClient(); InputStream fileIn = null; OutputStream fileOut = null;
try { if (port == null) { LOGGER.debug("Connect to FTP server on " + host + ":" + FTP.DEFAULT_PORT); ftpClient.connect(host); } else { LOGGER.debug("Connect to FTP server on " + host + ":" + port); ftpClient.connect(host,port); } int reply = ftpClient.getReplyCode(); if (!FTPReply.isPositiveCompletion(reply)) { LOGGER.error("FTP server refuses connection"); return; }
if (isAnonymous != null && isAnonymous) { username = ANONYMOUS_USER_NAME; password = ANONYMOUS_PASSWORD; } LOGGER.debug("Log in FTP server with username = " + username + ", password = " + password);
if (!ftpClient.login(username,password,null)) { LOGGER.error("Fail to log in FTP server with username = " + username + ", password = " +
password); ftpClient.logout(); return; }
//bug处理,ftpClient.storeFile返回false,文件名编码问题 // ftpClient.setControlEncoding("UTF-8"); if (FTPReply.isPositiveCompletion(ftpClient.sendCommand( "OPTS UTF8", "ON"))) {// 开启服务器对UTF-8的支持,如果服务器支持就用UTF-8编码,否则就使用本地编码(GBK). LOCAL_CHARSET = "UTF-8"; } ftpClient.setControlEncoding(LOCAL_CHARSET);
// Here we will use the BINARY mode as the transfer file type, // ASCII mode is not supportted. LOGGER.debug("Set type of the file, which is to upload, to BINARY."); ftpClient.setFileType(FTP.BINARY_FILE_TYPE);
if (isPASV != null && isPASV) { LOGGER.debug("Use the PASV mode to transfer file."); ftpClient.enterLocalPassiveMode(); } else { LOGGER.debug("Use the ACTIVE mode to transfer file."); ftpClient.enterLocalActiveMode(); }
if (StringUtils.isBlank(workingDirectory)) { workingDirectory = "/"; }
LOGGER.debug("Change current working directory to " + workingDirectory); changeWorkingDirectory(ftpClient,workingDirectory);
if (isUpload) { // upload if (StringUtils.isBlank(serverFileStoredName)) { serverFileStoredName = fileToUpload.getName(); } fileIn = new FileInputStream(fileToUpload); LOGGER.debug("Upload file : " + fileToUpload.getAbsolutePath() + " to FTP server with name : " + serverFileStoredName);
String fileName = new String(serverFileStoredName.getBytes(LOCAL_CHARSET), SERVER_CHARSET);
//将文件存储到ftp //报错:Software caused connection abort: socketwrite error // 关闭防火墙或者启用除jdk1.7之外的版本并直接开启被动传输模式,传输模式设置绿字部分。
if (!ftpClient.storeFile(fileName, fileIn)) { LOGGER.error("Fail to upload file, " + ftpClient.getReplyString()); } else { LOGGER.debug("Success to upload file."); } } else { // download // make sure the file directory exists File fileStored = new File(localFileStoredPath); if (!fileStored.getParentFile().exists()) { fileStored.getParentFile().mkdirs(); } fileOut = new FileOutputStream(fileStored); LOGGER.debug("Download file : " + fileNameToDownload + " from FTP server to local : " + localFileStoredPath); if (!ftpClient.retrieveFile(fileNameToDownload, fileOut)) { LOGGER.error("Fail to download file, " + ftpClient.getReplyString()); } else { LOGGER.debug("Success to download file."); } }
ftpClient.noop();
ftpClient.logout();
} finally { if (ftpClient.isConnected()) { try { ftpClient.disconnect(); } catch (IOException f) { } } if (fileIn != null) { try { fileIn.close(); } catch (IOException e) { } } if (fileOut != null) { try { fileOut.close(); } catch (IOException e) { } } } }
private static final boolean changeWorkingDirectory(FTPClient ftpClient, String workingDirectory) throws IOException{ if(!ftpClient.changeWorkingDirectory(workingDirectory)){ String [] paths = workingDirectory.split("/"); for(int i=0 ;i<paths.length ;i++){ if(!"".equals(paths[i])){ if(!ftpClient.changeWorkingDirectory(paths[i])){ ftpClient.makeDirectory(paths[i]); ftpClient.changeWorkingDirectory(paths[i]); } } } } return true; }
public static final void upload(Map<String, Object> serverCfg, String filePathToUpload, String fileStoredPath, String
fileStoredName) throws SocketException, IOException { upload(serverCfg, new File(filePathToUpload), fileStoredPath, fileStoredName); }
public static final void upload(Map<String, Object> serverCfg, File fileToUpload, String fileStoredPath, String
fileStoredName) throws SocketException, IOException { if(fileStoredPath!=null && !"".equals(fileStoredPath)){ serverCfg.put(WORKING_DIRECTORY, fileStoredPath); } upload(serverCfg, fileToUpload, fileStoredName); }
public static final void upload(String filePathToUpload, String fileStoredPath)throws SocketException, IOException { upload(serverCfg, filePathToUpload, fileStoredPath, ""); }
public static final void upload(File fileToUpload, String fileStoredPath)throws SocketException, IOException { upload(serverCfg, fileToUpload, fileStoredPath, ""); }
public static String values(String key) { String value = prop.getProperty(key); if (value != null) { return value; } else { return null; } }
} |
8:配置文件
SERVER_IP=** SERVER_PORT=21 USER_NAME= ** PASSWORD=** |