之前写过一个上传的方法,使用的是第三方jar包,这次使用springMVC内置的上传和富文本上传介绍,同时讲解链接ftp服务器的相关配置
ftpUtil的配置:
package com.mmall.until;
import org.apache.commons.net.ftp.FTPClient;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;
import java.util.List;
/**
* Created by Administrator on 2017/10/14.
*/
public class FTPUtil {
private static final 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");
public FTPUtil(String ip, int port, String user, String pwd) {
this.ip = ip;
this.port = port;
this.user = user;
this.pwd = pwd;
}
//返回上传成功还是失败
public static boolean uploadFile(List<File> fileList) throws IOException {
FTPUtil ftpUtil = new FTPUtil(ftpIp,21,ftpUser,ftpPass);
logger.info("开始链接ftp服务器!");
//不是所有的异常都要被捕获,像这个异常就需要抛出到业务层处理,根据业务情况
boolean result = ftpUtil.uploadFile("image",fileList);
logger.info("开始ftp服务器,结束上传,上传结果:{}");
return result;
}
private boolean uploadFile(String remotePath,List<File> fileList) throws IOException {
/**
* remotePath(远程文件名)的作用:
* ftp服务器在Linux服务器上是一个文件夹,如果要在它的下级创建文件,就需要这个文件夹
*/
boolean uploaded = true;//是否传了
FileInputStream fis = null;
//链接ftp服务器
if (conectServer(this.ip,this.port,this.user,this.pwd)){
try {
//更改工作目录
ftpClient.changeWorkingDirectory(remotePath);
//设置缓冲区
ftpClient.setBufferSize(1024);
ftpClient.setControlEncoding("UTF-8");
//设置文件类型为二进制文件类型,防止乱码
ftpClient.setFileType(ftpClient.BINARY_FILE_TYPE);
ftpClient.enterLocalPassiveMode();
for (File fileItem:fileList){
fis = new FileInputStream(fileItem);//创建input流
ftpClient.storeFile(fileItem.getName(),fis);
}
} catch (IOException e) {
logger.error("上传文件异常!",e);
uploaded = false;
e.printStackTrace();
}finally {
fis.close();
ftpClient.disconnect();
}
}
return uploaded;
}
//是否链接ftp成功
private boolean conectServer(String ip,int port,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服务器异常!",e);
}
return isSuccess;
}
private String ip;
private int port;
private String user;
private String pwd;
private FTPClient ftpClient;
public String getIp() {
return ip;
}
public void setIp(String ip) {
this.ip = ip;
}
public int getPort() {
return port;
}
public void setPort(int port) {
this.port = port;
}
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;
}
}
@controller层:
//文件上传
@RequestMapping(value = "upload.do")
@ResponseBody
public ServerResponse upload(HttpSession session,
@RequestParam(value = "upload_file", required = false) MultipartFile file,
HttpServletRequest request) {
User user = (User) session.getAttribute(Const.CURRENT_USER);
if (user == null) {
return ServerResponse.createByErrorMessage(ResponseCode.NEED_LOGIN.getCode(), "未登录,请强制登陆管理员!");
}
if (iUserService.checkAdminRole(user).isSuccess()) {
//填充业务
//文件上传后的路径,和webapp下index.jsp同级的文件夹
String path = request.getSession().getServletContext().getRealPath("upload");
String targetFileName = iFileService.upload(file, path);
String url = PropertiesUtil.getProperty("ftp.server.http.prefix") + targetFileName;
Map fileMap = Maps.newHashMap();
fileMap.put("uri", targetFileName);
fileMap.put("url", url);
return ServerResponse.createBySuccess(fileMap);
} else {
return ServerResponse.createByErrorMessage("无权限操作!");
}
}
@RequestMapping("richtext_img_upload.do")
@ResponseBody
public Map richtextImgUpload(HttpSession session, @RequestParam(value = "upload_file",required = false) MultipartFile file, HttpServletRequest request, HttpServletResponse response) {
Map resultMap = Maps.newHashMap();
User user = (User) session.getAttribute(Const.CURRENT_USER);
if (user == null) {
resultMap.put("success", false);
resultMap.put("msg", "请登录管理员");
return resultMap;
}
//富文本中对于返回值有自己的要求,我们使用是simditor所以按照simditor的要求进行返回
// {
// "success": true/false,
// "msg": "error message", # optional
// "file_path": "[real file path]"
// }
if (iUserService.checkAdminRole(user).isSuccess()) {
String path = request.getSession().getServletContext().getRealPath("upload");
String targetFileName = iFileService.upload(file, path);
if (StringUtils.isBlank(targetFileName)) {
resultMap.put("success", false);
resultMap.put("msg", "上传失败");
return resultMap;
}
String url = PropertiesUtil.getProperty("ftp.server.http.prefix") + targetFileName;
resultMap.put("success", true);
resultMap.put("msg", "上传成功");
resultMap.put("file_path", url);
response.addHeader("Access-Control-Allow-Headers", "X-File-Name");
return resultMap;
} else {
resultMap.put("success", false);
resultMap.put("msg", "无权限操作");
return resultMap;
}
}
dispatch-servlet.xml的配置:
<!-- 文件上传 -->
<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>
测试页:
<%@page contentType="text/html; charset=UTF-8" language="java" %>
<html>
<body>
<h2>Hello World!</h2>
springmvc上传文件
<form name="form1" action="/manage/product/upload.do" method="post" enctype="multipart/form-data">
<input type="file" name="upload_file" />
<input type="submit" value="springmvc上传文件" />
</form>
富文本图片上传文件
<form name="form2" action="/manage/product/richtext_img_upload.do" method="post" enctype="multipart/form-data">
<input type="file" name="upload_file" />
<input type="submit" value="富文本图片上传文件" />
</form>
</body>
</html>
上传逻辑的实现:
package com.mmall.service.UserServiceImpl;
import com.google.common.collect.Lists;
import com.mmall.service.IFileService;
import com.mmall.until.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 Administrator on 2017/10/14.
*/
@Service("iFileService")
public class FileServiceImpl implements IFileService {
private Logger logger = LoggerFactory.getLogger(FileServiceImpl.class);
public String upload(MultipartFile file,String path){
//拿到上传文件的原始文件名
String fileName = file.getOriginalFilename();
//扩展名
//abc.jpg
String fileExtensionName =fileName.substring(fileName.lastIndexOf(".")+1);
//为了防止名字重复的文件会被覆盖,采取如下拼接方式
String uploadFileName = UUID.randomUUID().toString()+"."+fileExtensionName;
logger.info("上传文件开始:上传的文件名{},上传的路径{},上传的新文件名{}",fileName,path,uploadFileName);
File fileDir = new File(path);
if (!fileDir.exists()){
//获得写的权限(在tomcat中创建文件,不一定有权限发布文件)
fileDir.setWritable(true);
//mkdirs 和 mkdir 的区别是创建多个和一个的区别
fileDir.mkdirs();
}
File targetFile = new File(path,uploadFileName);
try {
file.transferTo(targetFile);
//文件已经上传成功了
// 将targetFile上传到ftp服务器上
FTPUtil.uploadFile(Lists.newArrayList(targetFile));
//已经上传到ftp服务器上
// 上传完成后删除upload下面的文件
targetFile.delete();
} catch (IOException e) {
logger.error("上传文件异常!",e);
return null;
}
return targetFile.getName();
}
}