这里也是学习看别人的的代码,学习糅合了一下。

前面两个文件上传已经介绍了

首先需要两个jar文件

commons-io-2.5.jar

commons-fileupload-1.3.1.jar

当然版本根据自己需要选择

设置文件上传配置,在spring配置文件,加入文件上传配置,如果不是不考虑

<!--文件上传  -->
<bean id="multipartResolver" class="org.springframework.web.multipart.commons.CommonsMultipartResolver">
<property name="maxUploadSize" value="5000000"/>
<property name="defaultEncoding" value="UTF-8"/>
<property name="resolveLazily" value="true"/> 
</bean>

ftp文件上传首先要搭建ftp服务器,window参考

https://jingyan.baidu.com/article/574c5219d466c36c8d9dc138.html

linux参考

文件上传界面

<input type="file" id="fileSelect" name="file"/>
<input type="button" value="上传1" class="upload-file"/> 

用的ajaxfileupload.js插件,当然你也可以不用,具体参考我前面两篇文章

需要引用的js

jquery-2.1.1.js,ajaxfileupload.js

jquery好像1.7以上就可以

ajaxfileupload.js下载地址

https://github.com/carlcarl/AjaxFileUpload

js代码

//我这里是要求上传图片,做了图片校验
$(".upload-file").click(function(){
   //图片格式验证
   var headimg=$("#fileSelect").val();
   var index=headimg.lastIndexOf(".");
   var fileType=headimg.substring(index+1,headimg.length).toUpperCase();
   if(fileType=="JPG"||fileType=="JIF"||fileType=="PNG"||fileType=="JPEG"||fileType=="BMP"){//校验后缀
upload();
   }else{
$.alert("图片格式不对");
   }
});
 
 function upload(){ 
 $.ajaxFileUpload({
 url:"/fileController/upload.action",
 type:"post",
 secureuri:false,
 fileElementId:"fileSelect",
 dataType:"json",
 success:function(res,status){  
 if(res.success){
 $.alert("上传成功"+res.msg);//msg返回文件名
 }else{
 $.alert("请稍候再试");
 }
},
 error:function(){
 alert("请稍候再试");
 }
}); 
 }

spring controller  文件上传控制器

/** 文件上传处理 **/
 @Controller
 @RequestMapping("/fileController")
 public class FileController { 
//ftp文件上传的工具类   这里用道理Json类,就是一个返回值类,用以前段判断后台运行是什么状态,什么结果,不多解释
FtpUtils ftpUtils = new FtpUtils();
 
/**ftp文件上传*/
@RequestMapping("/upload")
@ResponseBody
public Json upload(@RequestParam(value = "file", required = false) MultipartFile file,HttpServletRequest request)
throws IllegalStateException, IOException {
Json json=new Json();
try {
//先上传本地  ftp要求文件路径,所以要先保存服务器,当然,你也可以使用InputStream  将MultipartFile file转成输入流处理
String path = request.getSession().getServletContext().getRealPath("/pages/upload");
File file1 = new File(path,file.getOriginalFilename());
file.transferTo(file1);
String fileurl = "ww";//远程路径  ftp上用来存放文件的文件夹
boolean status = ftpUtils.connect(fileurl);
if (status) {
if (ftpUtils.isExistDir(fileurl)) {//判断远程ftp是否存在该路径 
json =uploadPicture(file1, fileurl);
} else {
ftpUtils.mkDir(fileurl);//如果这个路径不存在就会自动创建
json=uploadPicture(file1, fileurl);
}
} else {
System.out.println("连接失败");
json.setSuccess(false);
}
ftpUtils.closeFtp();//关闭连接
} catch (Exception e) {

e.printStackTrace();
}
return json;
}




private Json uploadPicture(File file2, String date) throws Exception {
Json json=new Json();
ftpUtils.changeWorkingDirectory(date);//切换路径
json=ftpUtils.upload(file2);//上传文件
ftpUtils.closeFtp();//关闭
return json;
} }

下面是ftp工具类

package com.neutron.admin.util;


 import java.io.File;
 import java.io.FileInputStream;
 import java.io.IOException;
 import java.io.InputStream;


 import org.apache.commons.net.ftp.FTP;
 import org.apache.commons.net.ftp.FTPClient;
 import org.apache.commons.net.ftp.FTPReply;
 import org.springframework.stereotype.Component;


 import com.neutron.admin.model.dto.Json;


 @Component
 public class FtpUtils  {


private FTPClient ftp;


     /**
      * 
      * @param path
      *            上传到ftp服务器哪个路径下
      * @param addr
      *            地址
      * @param port
      *            端口号
      * @param username
      *            用户名
      * @param password
      *            密码
      * @return
      * @throws Exception
      */
     public boolean connect(String path) throws Exception {
         boolean result = false;
         ftp = new FTPClient();
         ftp.setControlEncoding("GBK");
         int reply;
         ftp.connect(Constant.ftpaddr, Constant.ftpport);//ftpaddr:FTP服务器ip  ftpport:端口    ftpUserName:用户名   ftppwd:密码//这里注意,如果项目放入linux服务器上运行,ip地址必须填127.0.0.1  要不然上传不上去。下面还要设置主动模式
        ftp.login(Constant.ftpUserName, Constant.ftppwd);
        ftp.setFileType(FTPClient.BINARY_FILE_TYPE);
        reply = ftp.getReplyCode();//ftp连接状态
        if (!FTPReply.isPositiveCompletion(reply)) {// 判断返回码是否合法  不合法断开
            ftp.disconnect();
            return result;
        }
        result = ftp.changeWorkingDirectory(path);//切换文件保存的工作路径去
        return result;
    }


    /**
     * 
     * @param file
     *            上传的文件或文件夹
     * @throws Exception
     */
    public Json upload(File file) throws Exception {
    Json json=new Json();
        if (file.isDirectory()) {//如果是一个目录
            ftp.makeDirectory(file.getName());


            ftp.changeWorkingDirectory(file.getName());

//下面这段代码是更新文件名,要不然如果上传文件同名,就会出问题,这里我用时间戳命名文件名
            int index=file.getName().lastIndexOf(".");//更新原理就是查找文件名倒数第一个“.”,“.”后面的就是后缀,然后前面的用时间戳替换
           

String newName=System.currentTimeMillis()+file.getName().substring(index,file.getName().length());
             ftp.rename(file.getName(), newName);          
            String[] files = file.list();
            for (int i = 0; i < files.length; i++) {
                try {
               File file1 = new File(file.getPath() + "\\" + files[i]);
               if (file1.isDirectory()) {
                   upload(file1);
                   ftp.changeToParentDirectory();
               } else {
                   File file2 = new File(file.getPath() + "\\" + files[i]);
                   FileInputStream input = new FileInputStream(file2);//主动模式,必须加入,要不然,项目放入linux服务器,会出现无法上传的问题
                   ftp.storeFile(file2.getName(), input);
                   input.close();
               } 
               json.setSuccess(true);
                } catch (Exception e) {
                    System.out.println(e.getMessage());
                }
            }


            
            if(file.exists()&&file.isFile()){ //因为刚才保存在服务器,然后上传ftp,所以要在上传后删除服务器的文件
    System.out.println("文件删除"+file.delete());   //删除成功 
            }
            json.setMsg(newName);//上传成功后返回文件的名字到前段,用于存储文件路径。因为文件路径是你定的,所以路径自己写,这里只返回文件名
        } else {
            try {
                File file2 = new File(file.getPath());
                FileInputStream input = new FileInputStream(file2);

ftp.enterLocalPassiveMode();//主动模式,必须加入,要不然,项目放入linux服务器,会出现无法上传的问题
//指定到服务器的文件名  
           


int index=file.getName().lastIndexOf(".");
                 String newName=System.currentTimeMillis()+file.getName().substring(index,file.getName().length());
                 ftp.rename(file.getName(), newName);              
                input.close();               
                if(file.exists()&&file.isFile()){
         System.out.println("文件删除"+file.delete());
                 }
                json.setMsg(newName);
                json.setSuccess(true);
            } catch (Exception e) {
                System.out.println(e.getMessage());
            }


        }
        
       
        return json;
    }


    /**
     * 关闭连接
     */
    public void closeFtp() {
        if (ftp.isConnected()) {
            try {
                ftp.disconnect();
            } catch (Exception e) {
                e.printStackTrace();
            }
        }
    }


    /**
     * 更改目录
     * 
     * @param path
     */
    public void changeWorkingDirectory(String path) {
        if (ftp.isConnected()) {
            try {
                ftp.changeWorkingDirectory(path);
            } catch (IOException e) {
                e.printStackTrace();
            }
        } else {
            System.out.println("未连接");
        }
    }


    /**
     * 判断ftp上是否存在路径
     * 
     * @return boolean
     */
    public boolean isExistDir(String path) {
        try {
            return ftp.changeWorkingDirectory(path);
        } catch (IOException e) {
            return false;
        }
    }


    /**
     * 在ftp上创建文件夹
     * 
     * @param dir
     *            文件夹名字
     */
    public void mkDir(String dir) {


        try {
            ftp.makeDirectory(dir);
        } catch (IOException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        }
    }
 }