In a project, file upload is often needed. The following process is the file upload step I used in a development process, which is applied to spring MVC file upload and docking with FTP server.
Add the bean needed to upload the file in pom.xml
<!-- https://mvnrepository.com/artifact/commons-fileupload/commons-fileupload -->
<dependency>
<groupId>commons-fileupload</groupId>
<artifactId>commons-fileupload</artifactId>
<version>1.2.2</version>
</dependency>
<dependency>
<groupId>commons-io</groupId>
<artifactId>commons-io</artifactId>
<version>2.0.1</version>
</dependency>
Add information such as file size and file encoding to dispatcher-servlet.xml
<!-- File upload -->
<bean id="multipartResolver" class="org.springframework.web.multipart.commons.CommonsMultipartResolver">
<property name="maxUploadSize" value="10485760"/> <!-- 10m -->
<property name="maxInMemorySize" value="4096" />
<property name="defaultEncoding" value="UTF-8"></property>
</bean>
Background upload process
FileService source code display
For more convenient use, I declare an IFileService interface class for background calls. Here is the code to implement the interface class
import com.google.common.collect.Lists;
import com.mmall.service.IFileService;
import com.mmall.util.FTPUtil;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.stereotype.Service;
import org.springframework.web.multipart.MultipartFile;
import java.io.File;
import java.io.IOException;
import java.util.UUID;
/**
* Created by xiao on 2018/1/21.
*/
@Service("iFileService")
public class FileServiceImpl implements IFileService {
//Logging
private Logger logger = LoggerFactory.getLogger(FileServiceImpl.class);
public String upload(MultipartFile file,String path){
String fileName = file.getOriginalFilename();
//Extension
String fileExtensionName = fileName.substring(fileName.lastIndexOf('.')+1);
//Use UUID to prevent duplicate file names and overwrite other people's files
String uploadFileName = UUID.randomUUID().toString() + "." + fileExtensionName;
logger.info("Start to upload the file. The name of the uploaded file:{},Upload path:{},New filename:{} ",fileName,path,uploadFileName);
//new file
File fileDir = new File(path);
//Determine whether the file exists, and create a new one if it does not exist
if(!fileDir.exists()){
//Make the file modifiable, because after Tomcat publishes the service, the permissions of the file may not be modifiable
fileDir.setWritable(true);
//dirs is used to solve the problem that if a folder is not created in the uploaded path, it will automatically create a folder
fileDir.mkdirs();
}
File targetFile = new File(path,uploadFileName);
try {
file.transferTo(targetFile);
//So far, the file has been uploaded to the server successfully
//The next step is to upload the file to the FTP server and connect with the FTP file server
FTPUtil.uploadFile(Lists.newArrayList(targetFile));
//File uploaded to FTP
//After uploading, delete the file under upload
targetFile.delete();
} catch (IOException e) {
logger.error("Upload file exception",e);
return null;
}
return targetFile.getName();
}
}
FTPUtil source code display
import org.apache.commons.net.ftp.FTP;
import org.apache.commons.net.ftp.FTPClient;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import javax.print.DocFlavor;
import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;
import java.util.List;
/**
* Created by xiao on 2018/1/21.
*/
public class FTPUtil {
private static Logger logger = LoggerFactory.getLogger(FTPUtil.class);
private static String ftpIp = PropertiesUtil.getProperty("ftp.server.ip");
private static String ftpUser= PropertiesUtil.getProperty("ftp.user");
private static String ftpPass = PropertiesUtil.getProperty("ftp.pass");
FTPUtil(String ip,int port,String user,String pwd){
this.ip = ip;
this.port = port;
this.pwd = pwd;
}
/**
* Methods of uploading files exposed to the outside world
* @param fileList
* @return
*/
public static boolean uploadFile(List<File> fileList) throws IOException {
FTPUtil ftpUtil = new FTPUtil(ftpIp,21,ftpUser,ftpPass);
logger.info("Start connection FTP The server");
//Throw the exception to the service layer and do not handle it here
boolean result = ftpUtil.uploadFile("img",fileList);
logger.info("Start connection FTP Server, end upload, upload results{}",result);
return result;
}
private boolean uploadFile(String remotePath,List<File> fileList) throws IOException {
boolean uploaded = true;
FileInputStream fis = null;
//Connect to FTP server
if(connectServer(this.getIp(),this.getUser(),this.getPwd())){
try {
ftpClient.changeWorkingDirectory(remotePath);
ftpClient.setBufferSize(1024);
ftpClient.setControlEncoding("UTF-8");
//Set to binary format to prevent garbled code
ftpClient.setFileType(FTP.BINARY_FILE_TYPE);
//Passive mode storage
ftpClient.enterLocalPassiveMode();
//Traverse file store
for(File fileItem : fileList){
//Convert files to streams
fis = new FileInputStream(fileItem);
//Call storeFile method to store
ftpClient.storeFile(fileItem.getName(),fis);
}
} catch (IOException e) {
logger.error("Upload file exception",e);
uploaded = false;
}
finally {
//Close connections and FileStream
fis.close();
ftpClient.disconnect();
}
}
return uploaded;
}
/**
* Connect to FTP server
* @param ip
* @param user
* @param pwd
* @return
*/
private boolean connectServer(String ip, String user,String pwd ){
boolean isSuccess = false;
ftpClient = new FTPClient();
try{
ftpClient.connect(ip);
isSuccess = ftpClient.login(user,pwd);
}catch (IOException e){
logger.error("FTP Server connection failed",e);
}
return isSuccess;
}
private String ip ;
private int port;
private String user;
private String pwd;
private FTPClient ftpClient ;
public int getPort() {
return port;
}
public void setPort(int port) {
this.port = port;
}
public String getIp() {
return ip;
}
public void setIp(String ip) {
this.ip = ip;
}
public static String getFtpTp() {
return ftpIp;
}
public static void setFtpTp(String ftpTp) {
FTPUtil.ftpIp = ftpTp;
}
public static String getFtpUser() {
return ftpUser;
}
public static void setFtpUser(String ftpUser) {
FTPUtil.ftpUser = ftpUser;
}
public static String getFtpPass() {
return ftpPass;
}
public static void setFtpPass(String ftpPass) {
FTPUtil.ftpPass = ftpPass;
}
public String getUser() {
return user;
}
public void setUser(String user) {
this.user = user;
}
public String getPwd() {
return pwd;
}
public void setPwd(String pwd) {
this.pwd = pwd;
}
public FTPClient getFtpClient() {
return ftpClient;
}
public void setFtpClient(FTPClient ftpClient) {
this.ftpClient = ftpClient;
}
}