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;
    }

}
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值