在项目的开发过程当中,文件的上传是常见的操作,此处做个记录,方便以后查
看。
一.流程分析
二 .SpringMVC文件上传
1.导入jar包
在web开发当中我们是使用Apache fileupload组件来实现文件的上传的,在SpringMVC当中对这个组件进行了封装,但是底层还是Apache fileupload组件,springmvc中由MultipartFile接口来实现文件上传,MultipartFile对象被用来接收要前端传过来的数据文件,SpringMVC会将发送的文件绑定到multipartFile对象上。
导入jar包
commons-fileupload
commons-io
commons-io可以不用自己导入,maven会自动导入对应版本的jar
commons-fileupload
commons-fileupload
1.3.2
commons-io
commons-io
2.0.1
2.MultipartResolver解析
在SpringMVC当中使用MultipartFile对象作为参数,来接受前端传过来的文件,将文件写入到本地当中,实现文件的上传,要想使用该参数,还需要在SpringMVC的配置文件当中配置MultipartResolver。
3.coding
#####################使用SpringMVC##########################
@Controller
@RequestMapping("/manage/product")
public class ProductManagerController {
@Autowired
private IUserService iUserService;
@Autowired
private IFileService iFileService;
//文件的上传,使用MultipartFile参数来接受要发送的数据文件,SpringMVC会将发送的文件绑定到multipartFile对象上
@RequestMapping("upload.do")
@ResponseBody
public ServerResponse upload(HttpSession session, @RequestParam(value = "upload_file",required = false)MultipartFile multipartFile){
User user= (User) session.getAttribute(Const.CURRENT_USER);
if(user==null ){
return ServerResponse.createByErrorMessage("用户未登陆,请先登陆");
}
if(!iUserService.checkUserRole(user).isSuccess()){
return ServerResponse.createByErrorMessage("该用户不是管理员,无权限操作");
}
if(multipartFile.isEmpty()){
return ServerResponse.createByErrorMessage("要上传的问文件为空");
}
//获取Servlet的上下文,表示要上传的地方是哪里
String path=session.getServletContext().getRealPath("/WEB-INF/upload");
String targetName=iFileService.upload(multipartFile,path);
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);
return ServerResponse.createBySuccess(targetName);
}
}
###################使用富文本###################
/**
* 富文本当中对返回值有自己的要求,我们使用的富文本是simditor,所以按照simditor的要求返回,此处我们让返回值是一个Map即可,无需专门去创建一个simditor对象
* https://simditor.tower.im/docs/doc-config.html
* {
* "success": true/false,
* "msg": "error message", # optional
* "file_path": "[real file path]"
* }
* 除此之外对response也有要求:response.addHeader("Access-Control-Allow-Headers","X-File-Name");
*/
@RequestMapping("rich_img_upload.do")
@ResponseBody
public Map richImgUpload(HttpSession session, @RequestParam(value = "upload_file",required = false)MultipartFile multipartFile, HttpServletResponse response){
User user= (User) session.getAttribute(Const.CURRENT_USER);
Map resultMap= Maps.newHashMap();
if(user==null ){
resultMap.put("success",false);
resultMap.put("msg","用户未登陆,请先登陆");
return resultMap;
}
if(!iUserService.checkUserRole(user).isSuccess()){
resultMap.put("success",false);
resultMap.put("msg","该用户不是管理员,无权限操作");
return resultMap;
}
if(multipartFile.isEmpty()){
resultMap.put("success",false);
resultMap.put("msg","要上传的是空文件");
return resultMap;
}
//获取Servlet的上下文,表示要上传的地方是哪里
String path=session.getServletContext().getRealPath("/WEB-INF/upload");
String targetName=iFileService.upload(multipartFile,path);
if(StringUtils.isBlank(targetName)){
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);
resultMap.put("file_path",targetName);
return resultMap;
}
@Service("iFileService")
public class IFileServiceImpl implements IFileService {
private static Logger logger= LoggerFactory.getLogger(IFileServiceImpl.class);
public String upload(MultipartFile multipartFile,String path){
String originalFilename=multipartFile.getOriginalFilename();
String fileExtensionName=originalFilename.substring(originalFilename.lastIndexOf("."));
String uploadFileName= UUID.randomUUID().toString()+fileExtensionName;
File targetFile=new File(path,uploadFileName);
if(!targetFile.exists()){
targetFile.setWritable(true);//设置对文件的写权限
targetFile.mkdirs();
}
try {
multipartFile.transferTo(targetFile);//上传文件完成
//todo 上传文件到发图片服务器(将根目录下的targetFile上传到FTP服务器上)
// FTPUtil.uploadFile(Lists.newArrayList(targetFile));
//todo 上传完毕后删除刚刚上传的文件,文件夹不会删除
// targetFile.delete();
} catch (IOException e) {
logger.info("文件上传失败",e);
}
return targetFile.getName();
}
}
三.上传文件到FTP服务器
package com.mmall.util;
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;
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");
private String ip;
private int port;
private String user;
private String pwd;
private FTPClient ftpClient;
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 fileList) throws IOException {
FTPUtil ftpUtil = new FTPUtil(ftpIp,21,ftpUser,ftpPass);
logger.info("开始连接ftp服务器");
/**
* 注意此处的remotePath的根目录是我们设置的用户根目录(/ftpfile/mmall)
* 此处是上传到/ftpfile/mmall/img下面,当然也可以直接写img,ftpClient会识别到根是/ftpfile/mmall
* img这个文件夹如果不存在会存在在根下面,如果存在,但是没权限则不会写入(根目录也不会),此时授权即可:chmod xxx fileName
*/
boolean result = ftpUtil.uploadFile("/img1",fileList);
logger.info("结束连接ftp服务器,结束上传,上传结果:{}",result);
return result;
}
private boolean uploadFile(String remotePath,List fileList) throws IOException {
boolean uploaded = true;
FileInputStream fis = null;
//连接FTP服务器
//ftpClient.enterLocalPassiveMode();
if(connectServer(this.ip,this.port,this.user,this.pwd)){
try {
ftpClient.changeWorkingDirectory(remotePath);//相当与cd remotePath,相当于切换到remotePath目录下
ftpClient.setBufferSize(1024);
ftpClient.setControlEncoding("UTF-8");
ftpClient.setFileType(FTPClient.BINARY_FILE_TYPE);
//ftpClient.enterLocalPassiveMode();
for(File fileItem : fileList){
fis = new FileInputStream(fileItem);
ftpClient.storeFile(fileItem.getName(),fis);
}
} catch (IOException e) {
logger.error("上传文件异常",e);
uploaded = false;
e.printStackTrace();
} finally {
fis.close();
ftpClient.disconnect();
}
}
return uploaded;
}
private boolean connectServer(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;
}
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;
}
}