SpringMVC实现FTP服务器之图片和富文本上传

上传流程为:

jsp(上传文件)->springMVC的servlet.xml(解析成二进制Mulitfile)->Controller->service(连接ftp,文件打包按格式二进制流上传)->ftp
注:本文的代码是我mvc结构的代码,包括:jsp,Controller,service实现类,及工具类,property配置文件,没有写出接口和Controller内的接口对象的注入,望周知!!!

一、图片上传

jsp:

<%--enctype(编码方式)必须要声明 name对应controller里的文件参数注解里的value--%>
<%-- @RequestParam(value = "upload_file",required = false) MultipartFile file--%>

<form name="form1" action="/manage/product/upload.do" enctype="multipart/form-data" method="post">
    <input type="file" name="upload_file">
    <button type="submit">SpringMVC上传文件</button>
   <%-- <input type="submit" value="SpringMVC上传文件">--%>
</form>

springMVC-servlet.xml:

<!-- 文件上传 -->
    <bean id="multipartResolver" class="org.springframework.web.multipart.commons.CommonsMultipartResolver">
        <property name="maxUploadSize" value="10485760"/> <!--文件上传最大size 10m -->
        <property name="maxInMemorySize" value="4096" /> <!--在内存中最大的size,上传文件时会使用内存-->
        <property name="defaultEncoding" value="UTF-8"></property>
    </bean>

Controller:

//SpringMVC,图片文件上传,MultipartFile为SpringMVC封装的方法
    @RequestMapping("upload.do")
    @ResponseBody  //序列化成json用
    public String upload( @RequestParam(value = "upload_file",required = false) MultipartFile file, HttpServletRequest request){
        String path = request.getSession().getServletContext().getRealPath("upload");
        String targetFileName = iFileService.upload(file,path);
        return targetFileName;
    }

Service实现类

@Service(value = "iFileService")
public class FileServiceimpl implements IFileService {
    public String upload(MultipartFile file,String path){
        String fileName = file.getOriginalFilename(); //拿到上传文件的原始文件名
        //获取扩展名,从文件名的最后一个.获取.之后的字符串即扩展名
        String fileExtensionName = fileName.substring(fileName.lastIndexOf(".")+1);
        //为了防止不同用户上传的文件名重复,所以用UUID.扩展名
        String uploadFileName = UUID.randomUUID().toString()+"."+fileExtensionName;

        File fileDir = new File(path);
        if (!fileDir.exists()){ //如果这个文件不存在,就创建
            fileDir.setWritable(true); //付权限,让这个文件可写
            //fileDir.mkdir();  上传文件时,如果目录就一级时可以用
            fileDir.mkdirs();
        }
        File targetFile = new File(path,uploadFileName);

        try {
            file.transferTo(targetFile);
            //到这为止文件已经上传成功
            //todo 将targetfile上传到ftp服务器
            //用guava将文件目标文件上传
            FTPUtil.uploadFile(Lists.newArrayList(targetFile));
            //执行完上面表示已经上传到FTP服务器上了
            //todo 上传之后,删除刚创建好的upload下面的文件
            targetFile.delete();
        } catch (IOException e) {
            logger.error("上传文件异常",e);
        }

        return targetFile.getName();
    }
}

工具类

public class FTPUtil {
    private static String ftpIp = "127.0.0.1";
    private static String ftpUser = "ninka";
    private static String ftpPass = "ninka";

    private FTPClient ftpClient; //创建一个ftp客户端对象
    public FTPClient getFtpClient() {
        return ftpClient;
    }
    public void setFtpClient(FTPClient ftpClient) {
        this.ftpClient = ftpClient;
    }
    //把具体逻辑封装到private方法,remotePath表示要上传到的文件夹w
    public boolean uploadFile(List<File> fileList) throws IOException {
        String remotePath = "img";
        boolean uploaded = true;
        FileInputStream fis = null;
        //连接FTP服务器
        if (connectServer(ftpIp,21,ftpUser,ftpPass)){
            System.out.println("开始连接ftp服务器");
            try {
                //设置需不需要切换文件夹
                ftpClient.changeWorkingDirectory(remotePath);
                //设置缓冲区
                ftpClient.setBufferSize(1024);
                //设置ftp字符集
                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
                uploaded = false;
            }finally {
                //关闭流
                fis.close();
                //关闭连接,防止打开时间长了,出现异常
                ftpClient.disconnect();
            }
        }
        System.out.println("开始连接ftp服务器,结束上传,上传结束:{}");
        return uploaded;
    }
    //连接FTP服务器
    private boolean connectServer(String ip,int port,String user,String pwd){
        FTPClient ftpClient = new FTPClient();
        boolean isSuccess = false;
        try {
            ftpClient.connect(ip);
            isSuccess = ftpClient.login(user,pwd);
            System.out.println("连接服务器成功");
            this.setFtpClient(ftpClient);
        } catch (IOException e) {
            logger.error("连接服务器异常",e);
        }
        return isSuccess;
    }
}

二、富文本上传
Controller

//富文本中对于返回值有自己的要求,我们使用的simditor所以按照simditor的要求来返回
        /*{
            "success": true/false,
                "msg": "error message", # optional
            "file_path": "[real file path]"
        }*/
//SpringMVC,富文本图片文件上传
    @RequestMapping("richtext_image_upload.do")
    @ResponseBody
    public Map richtextImageUpload(HttpSession session
            , @RequestParam(value = "upload_file",required = false) MultipartFile file
            , HttpServletRequest request
            , HttpServletResponse response){
     String path = request.getSession().getServletContext().getRealPath("upload");
            String targetFileName = iFileService.upload(file,path);
            if (StringUtils.isBlank(targetFileName)){
                map.put("success",false);
                map.put("msg","上传失败");
                return map;
            }
            //拼接和前端约定的url
            String url = PropertiesUtil.getProperty("ftp.server.http.prefix");
            map.put("success",true);
            map.put("msg","上传富文本文件成功");
            map.put("file_path",url);
            //修改下response头,前端有些插件要求对后端返回的 有要求
            response.addHeader("Access-Controll-Allow-Headers","X-File-Name");
            return map;  
 }
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值