springMVC上传,富文本上传和ftp服务器的配置
来源:互联网 发布:淘宝拍视频用什么软件 编辑:程序博客网 时间:2024/05/29 18:53
之前写过一个上传的方法,使用的是第三方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(); }}
阅读全文
0 0
- springMVC上传,富文本上传和ftp服务器的配置
- SpringMVC实现FTP服务器之图片和富文本上传
- 百度ueditor富文本--图片保存路径的配置以及上传到远程服务器
- YII中Ueditor富文本编辑器文件和图片上传的配置
- YII中Ueditor富文本编辑器文件和图片上传的配置
- 百度ueditor富文本--配置图片上传
- ueditor+requirejs+springMVC+七牛(富文本编辑器图片上传到指定服务器)
- FTP服务器的上传
- 富文本图片上传
- 富文本 文件上传
- FTP 服务器的上传和下载
- SpringMvc 文件上传并且实现与ftp服务器的对接
- 富文本编辑器上传图片的问题
- 百度富文本图片上传路径配置(非项目路径)
- 手把手教你百度富文本编辑器的相关配置包括图片上传(for jsp)
- 手把手教你百度富文本编辑器的相关配置包括图片上传(for jsp)
- FTP服务器文件的上传,下载和获取
- 百度富文本编辑器UEditor的使用和他的图片上传
- POJ 3061 Subsequence
- 登录注册mvp模式
- qqqqqqqqqqqq
- RecyclerView上拉刷新,下拉加载
- chrome插件开发
- springMVC上传,富文本上传和ftp服务器的配置
- 第三部分:Idea重构总结
- 给大家介绍一下,这是twitter的创始人@
- 需要有效的董事会
- python numpy
- VMware Workstation 12 Pro 虚拟机安装步骤详解
- JavaScript高级程序设计 Chapter 7 关于函数、闭包的笔记和理解
- MSC-Generator 的语法
- 用虚拟机安装linux