Springmvc文件上传

文件上传

一、Springmvc文件上传到ftp服务器

FileServiceImpl:

package com.hcxmall.service.impl;

import com.google.common.collect.Lists;
import com.hcxmall.service.IFileService;
import com.hcxmall.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;

/**
 * 文件上传
 *
 * @author HCX
 * @create 2017 - 11 - 16 15:01
 */
@Service("iFileService")
public class FileServiceImpl implements IFileService{

    private Logger logger = LoggerFactory.getLogger(FileServiceImpl.class);

    @Override
    public String upload(MultipartFile file,String path){
        String fileName = file.getOriginalFilename();
        //获取扩展名
        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()){
            //赋予权限:可写
            fileDir.setWritable(true);
            //makedir():当前级别
            //makedirs():如果上传的文件所在的文件夹是-a-b-c-d,上传到服务器 这些目录都没有,则使用makedirs()
            fileDir.mkdirs();
        }
        File targetFile = new File(path,uploadFileName);

        try {
            file.transferTo(targetFile);
            //文件已经上传成功了

            //将targetFile上传到我们的FTP服务器上
            FTPUtil.uploadFile(Lists.newArrayList(targetFile));

            //上传完之后,删除upload下面的文件
            targetFile.delete();

        } catch (IOException e) {
            logger.error("上传文件异常",e);
            return null;
        }

        return targetFile.getName();
    }
}

FTPUtil:

package com.hcxmall.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;

/**
 * 文件上传到服务器
 *
 * @author HCX
 * @create 2017 - 11 - 16 15:36
 */
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<File> fileList) throws IOException {
        //port是固定的21
        FTPUtil ftpUtil = new FTPUtil(ftpIp,21,ftpUser,ftpPass);
        logger.info("开始连接ftp服务器");
        //传到ftp服务器文件夹下的img文件夹
        boolean result = ftpUtil.uploadFile("img",fileList);

        logger.info("开始连接ftp服务器,结束上传,上传结果:{}");
        return result;
    }

    /**
     *
     * @param remotePath 远程路径:上传到ftp服务器上,ftp服务器在Linux下是一个文件夹,
     *                   如果需要上传到ftp文件夹中再下一层文件的话,就需要使用remotePath,使上传的路径多一些
     * @param fileList
     * @return
     * @throws IOException
     */
    private boolean uploadFile(String remotePath,List<File> fileList) throws IOException {
        boolean uploaded = true;
        FileInputStream fis = null;
        //连接FTP服务器
        if(connectServer(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);
                    //存储文件
                    ftpClient.storeFile(fileItem.getName(),fis);
                }
            } catch (IOException e) {
                logger.error("上传文件异常",e);
                uploaded = false;
                e.printStackTrace();
            }finally {
                //关闭流
                fis.close();
                //释放连接
                ftpClient.disconnect();
            }
        }
        return uploaded;

    }

    /**
     * 连接ftp服务器
     * @param ip
     * @param port
     * @param user
     * @param pwd
     * @return
     */
    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;
    }
}

上传到ftp服务器的一些配置信息hcxmall.properties:

ftp.server.ip=182.92.82.103
ftp.user=hcxmallftp
ftp.pass=ftppassword
#搭建的图片服务器的前缀
ftp.server.http.prefix=http://img.happymmall.com/

读取properties文件的工具类:

package com.hcxmall.util;

import org.apache.commons.lang.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import java.io.IOException;
import java.io.InputStreamReader;
import java.util.Properties;

/**
 * 配置文件工具类
 * @author HCX
 * @create 2017 - 11 - 15 18:28
 */
public class PropertiesUtil {

    private static Logger logger = LoggerFactory.getLogger(PropertiesUtil.class);

    private static Properties props;

    //在tomcat启动时读取里面的配置:使用静态代码块
    //执行顺序:静态代码块(在类被加载的时候执行且仅执行一次)>普通代码块>构造代码块
    //静态代码块:一般用于初始化静态变量。
    static{
        String fileName = "hcxmall.properties";
        props = new Properties();
        try {
            props.load(new InputStreamReader(PropertiesUtil.class.getClassLoader().getResourceAsStream(fileName),"UTF-8"));
        } catch (IOException e) {
            logger.error("配置文件读取异常",e);
        }
    }

    /**
     * 获取hcxmall.propeties文件中的信息:通过key获取value
     * @param key
     * @return
     */
    public static String getProperty(String key){
        String value = props.getProperty(key.trim());
        if(StringUtils.isBlank(value)){
        return null;
    }
        return value.trim();
}

    public static String getProperty(String key,String defaultValue){
        String value = props.getProperty(key.trim());
        if(StringUtils.isBlank(value)){
            value = defaultValue;
        }
        return value.trim();
    }
}

调用:

/**
 * 文件上传
 * @param file
 * @param request
 * @return
 */
@RequestMapping("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.createByErrorCodeMessage(ResponseCode.NEED_LOGIN.getCode(),"用户未登录,请登录管理员");
    }
    if(iUserService.checkAdminRole(user).isSuccess()){
        //上传到upload文件夹,此目录为webapp下的,即跟WEB-INF同级
        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("无权限操作");
    }

}

二、富文本文件上传

富文本中对于返回值有自己的要求,这里使用simditor 所以按照simditor的要求进行返回 该种富文本上传只针对simditor插件:

{
   "success":true/false,
    "msg":"error message",# optional
   "file_path":"[real file path]"
 }

demo:

@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;
    }
    
    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",false);
        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;
    }

}

附上之前做项目时写的文件上传demo,只是上传到本地,没有上传到ftp服务器:

文件上传工具类:

package com.xzkj.hrdc.sys.utils;

import com.xzkj.hrdc.sys.bean.FileList;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Controller;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.web.multipart.commons.CommonsMultipartFile;

import java.io.File;
import java.io.IOException;

/**
 * Created by HCX on 2017/7/13.
 * 文件上传工具类
 */
@Controller
@Transactional
public class FileUploadUtils {

    @Autowired
    FileListUtils fileListUtils;

    @Value("#{configProperties['locationUrl']}") //locationUrl=http://192.168.1.113:8080/upload/
    private String fileUrlPrefix;//文件远程访问路径前缀

    @Value("#{configProperties['photoURL']}") //D:/photos/
    private String filePathPrefix;//文件在服务器上的存储路径前缀

    public static String SEPARATOR = ",";

    public static final String FILE_TYPE_DOC = "文档";
    public static final String FILE_TYPE_PIC = "图片";

    //客户管理
    public static final String CUSTOMER_SIGN_ONE = "客户-1";

    //合同管理:签约部分
    public static final String CONTRACT_SIGN_ONE = "合同-签约-1";
    public static final String CONTRACT_SIGN_TWO = "合同-签约-2";
    public static final String CONTRACT_SIGN_THREE = "合同-签约-3";


    //上传文件
    public boolean uploadFile(CommonsMultipartFile[] files, Integer customerId, String fileType, String fileSource) throws IOException {
        return uploadFile(files, null, customerId, fileType, fileSource);
    }

    public boolean uploadFile(CommonsMultipartFile[] files, String[] names, Integer customerId, String fileType, String fileSource) throws IOException {
        return fileUp( files,  names, customerId, null,  fileType, fileSource);
         
    }


    public boolean uploadSelfFile(CommonsMultipartFile[] files, String[] names, String selfId, String fileType, String fileSource) throws IOException {
        return fileUp( files,  names, null, selfId,  fileType, fileSource);
    }


    public boolean fileUp(CommonsMultipartFile[] files, String[] names, Integer customerId, String selfId, String fileType, String fileSource)throws IOException{
        if (null != files && files.length > 0) {
            if (names == null || (names != null && files.length == names.length)) {
                for (int i = 0; i < files.length; i++) {
                    if (files[i] != null) {
                        String originalFileName = files[i].getOriginalFilename();//拿到文件上传时的名字
                        String[] splits = originalFileName.split("\\.");//根据.切割文件名和后缀
                        String suffix = "";
                        String fileName = splits[0];
                        if (splits.length > 1) {
                            suffix = "." + splits[splits.length - 1];
                        }
                        String fileNameOnServer = IDUtils.genImageName() + suffix;
                        /**
                         * 创建文件在服务器上的路径
                         filePathPrefix:在服务器上的存储路径(即在服务器上的哪个文件夹)
                         fileNameOnServer:目标文件名
                         */
                        File newFile = new File(filePathPrefix, fileNameOnServer);
                        files[i].transferTo(newFile);
                        if (names != null) {
                            fileName = names[i];
                        }
                        if(customerId!=null){
                            fileListUtils.insertOne(new FileList(customerId, fileUrlPrefix + fileNameOnServer, fileName, fileType, fileSource));

                        }
                        if(selfId!=null){
                            fileListUtils.insertSelfOne(new FileList(selfId, fileUrlPrefix + fileNameOnServer, fileName, fileType, fileSource));

                        }
                     }
                }
                return true;
            }
        }
        return false;
    }
    
}

调用:

//编辑签约列表信息
@RequestMapping("/editSignManage")
@ResponseBody
@Transactional
public Result editSignManage(SignManage signManage,
                             @RequestParam(value = "file1", required = false) CommonsMultipartFile[] file1, @RequestParam(value = "name1", required = false) String[] name1,
                             @RequestParam(value = "file2", required = false) CommonsMultipartFile[] file2, @RequestParam(value = "name2", required = false) String[] name2,
                             @RequestParam(value = "file3", required = false) CommonsMultipartFile[] file3, @RequestParam(value = "name3", required = false) String[] name3,
                             HttpServletRequest request) throws IOException {

    //前端要给的数据:customerId,signManageId
    //前端传递客户id
    Map<String, Object> resultMap=(Map<String, Object>)request.getAttribute("data");
    if (signManage.getCustomerId() != null) {
        fileUploadUtils.uploadFile(file1, name1, signManage.getCustomerId(), "图片", fileUploadUtils.CONTRACT_SIGN_ONE);
        fileUploadUtils.uploadFile(file2, name2, signManage.getCustomerId(), "图片", fileUploadUtils.CONTRACT_SIGN_TWO);
        fileUploadUtils.uploadFile(file3, name3, signManage.getCustomerId(), "图片", fileUploadUtils.CONTRACT_SIGN_THREE);
    }
    if (signManage.getSignManageId() == null) {
        //插入
        boolean isSuccess = signManageService.addSignManage(signManage,resultMap);
        if (!isSuccess)
            return new Result(StatusCode.E_PARAM, "添加失败");
        return new Result(StatusCode.OK, "添加成功");
    } else {
        //更新
        boolean isSuccess = signManageService.updateSignManage(signManage,resultMap);
        if (!isSuccess)
            return new Result(StatusCode.E_PARAM, "编辑失败");
        return new Result(StatusCode.OK, "编辑成功");
    }

}

生成图片名字工具类:

public class IDUtils {

    /**
     * 图片名生成
     */
    public static String genImageName() {
        //取当前时间的长整形值包含毫秒
        //long millis = System.currentTimeMillis();
        long millis = System.nanoTime();
        //加上三位随机数
        Random random = new Random();
        int end3 = random.nextInt(999);
        //如果不足三位前面补0
        String str = millis + String.format("%03d", end3);
        
        return str;
    }
    
    /**
     * 商品id生成
     */
    public static long genItemId() {
        //取当前时间的长整形值包含毫秒
        long millis = System.currentTimeMillis();
        //long millis = System.nanoTime();
        //加上两位随机数
        Random random = new Random();
        int end2 = random.nextInt(99);
        //如果不足两位前面补0
        String str = millis + String.format("%02d", end2);
        long id = new Long(str);
        return id;
    }

}
©著作权归作者所有,转载或内容合作请联系作者
  • 序言:七十年代末,一起剥皮案震惊了整个滨河市,随后出现的几起案子,更是在滨河造成了极大的恐慌,老刑警刘岩,带你破解...
    沈念sama阅读 161,192评论 4 369
  • 序言:滨河连续发生了三起死亡事件,死亡现场离奇诡异,居然都是意外死亡,警方通过查阅死者的电脑和手机,发现死者居然都...
    沈念sama阅读 68,186评论 1 303
  • 文/潘晓璐 我一进店门,熙熙楼的掌柜王于贵愁眉苦脸地迎上来,“玉大人,你说我怎么就摊上这事。” “怎么了?”我有些...
    开封第一讲书人阅读 110,844评论 0 252
  • 文/不坏的土叔 我叫张陵,是天一观的道长。 经常有香客问我,道长,这世上最难降的妖魔是什么? 我笑而不...
    开封第一讲书人阅读 44,471评论 0 217
  • 正文 为了忘掉前任,我火速办了婚礼,结果婚礼上,老公的妹妹穿的比我还像新娘。我一直安慰自己,他们只是感情好,可当我...
    茶点故事阅读 52,876评论 3 294
  • 文/花漫 我一把揭开白布。 她就那样静静地躺着,像睡着了一般。 火红的嫁衣衬着肌肤如雪。 梳的纹丝不乱的头发上,一...
    开封第一讲书人阅读 40,891评论 1 224
  • 那天,我揣着相机与录音,去河边找鬼。 笑死,一个胖子当着我的面吹牛,可吹牛的内容都是我干的。 我是一名探鬼主播,决...
    沈念sama阅读 32,068评论 2 317
  • 文/苍兰香墨 我猛地睁开眼,长吁一口气:“原来是场噩梦啊……” “哼!你这毒妇竟也来了?” 一声冷哼从身侧响起,我...
    开封第一讲书人阅读 30,791评论 0 205
  • 序言:老挝万荣一对情侣失踪,失踪者是张志新(化名)和其女友刘颖,没想到半个月后,有当地人在树林里发现了一具尸体,经...
    沈念sama阅读 34,539评论 1 249
  • 正文 独居荒郊野岭守林人离奇死亡,尸身上长有42处带血的脓包…… 初始之章·张勋 以下内容为张勋视角 年9月15日...
    茶点故事阅读 30,772评论 2 253
  • 正文 我和宋清朗相恋三年,在试婚纱的时候发现自己被绿了。 大学时的朋友给我发了我未婚夫和他白月光在一起吃饭的照片。...
    茶点故事阅读 32,250评论 1 265
  • 序言:一个原本活蹦乱跳的男人离奇死亡,死状恐怖,灵堂内的尸体忽然破棺而出,到底是诈尸还是另有隐情,我是刑警宁泽,带...
    沈念sama阅读 28,577评论 3 260
  • 正文 年R本政府宣布,位于F岛的核电站,受9级特大地震影响,放射性物质发生泄漏。R本人自食恶果不足惜,却给世界环境...
    茶点故事阅读 33,244评论 3 241
  • 文/蒙蒙 一、第九天 我趴在偏房一处隐蔽的房顶上张望。 院中可真热闹,春花似锦、人声如沸。这庄子的主人今日做“春日...
    开封第一讲书人阅读 26,146评论 0 8
  • 文/苍兰香墨 我抬头看了看天上的太阳。三九已至,却和暖如春,着一层夹袄步出监牢的瞬间,已是汗流浃背。 一阵脚步声响...
    开封第一讲书人阅读 26,949评论 0 201
  • 我被黑心中介骗来泰国打工, 没想到刚下飞机就差点儿被人妖公主榨干…… 1. 我叫王不留,地道东北人。 一个月前我还...
    沈念sama阅读 35,995评论 2 285
  • 正文 我出身青楼,却偏偏与公主长得像,于是被迫代替她去往敌国和亲。 传闻我的和亲对象是个残疾皇子,可洞房花烛夜当晚...
    茶点故事阅读 35,812评论 2 276

推荐阅读更多精彩内容

  • Spring Cloud为开发人员提供了快速构建分布式系统中一些常见模式的工具(例如配置管理,服务发现,断路器,智...
    卡卡罗2017阅读 134,106评论 18 139
  • 发现 关注 消息 iOS 第三方库、插件、知名博客总结 作者大灰狼的小绵羊哥哥关注 2017.06.26 09:4...
    肇东周阅读 11,635评论 4 59
  • springMVC 简单的文件上传 (图片或者文件) 这是controller层 对应工具类 ,这里面所需要包都是...
    山水风情阅读 297评论 0 0
  • 解决方案一:CommonsMultipartResolver 说明:该方案能够适用于servlet-3.0之前版本...
    王千博1990阅读 3,431评论 0 0
  • 一.ES6环境搭建 1.首先安装babel-cli(用于在终端使用babel) npm install babel...
    程序员小布的养生之道阅读 508评论 0 50