最完整HTML+springboot实现本地上传文件到ftp服务器

1搭建环境

IDEA+ windows10

image.png

2HTML页面

upload.html




    
    Title


    
选择文件

success.html




    
    上传成功


    文件上传成功!
    


wrong.html




    
    错误


    文件上传失败!
  


3 Controller 获取html上传的multipartfile

controller 接受html传来的文件后 先将该文件存放在本地tomcat某目录下(具体可以自行打印文件的路径查看)。
然后读取本地文件的路径和文件名(文件名经过了sha256加密) 新建输入流
调用FTPUtil的上传接口 上传 到服务器上同时删除本地的缓存文件
上传成功则跳转success界面可继续添加
否则进入wrong界面
ps:本例中只针对ipa 和mount文件进行上传

package com.example.demo.controller;

import com.example.demo.util.FTPUtil;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.multipart.MultipartFile;
import javax.servlet.http.HttpServletRequest;
import java.io.File;
import java.io.FileInputStream;
import java.io.InputStream;
import java.security.MessageDigest;
import java.text.SimpleDateFormat;
import java.util.Date;

@Controller
@RequestMapping("/app/")
public class UploadController {

    @Value("${upload.host}")
    private String host;

    @Value("${upload.port}")
    private int port;

    @Value("${upload.userName}")
    private String userName;

    @Value("${upload.password}")
    private String password;

    @Value("${upload.basePath}")
    private String basePath = "/";

    private String filePath;

    @RequestMapping("upload")
    public String upload(MultipartFile uploadFile, HttpServletRequest req){
        SimpleDateFormat sd = new SimpleDateFormat("yyyy/MM/dd");
        String realPath = req.getSession().getServletContext().getRealPath("/uploadFile");
        String format = sd.format(new Date());
        File file = new File(realPath + format);
        if (!file.isDirectory()){
            file.mkdirs();
        }
        String oldName = uploadFile.getOriginalFilename();
        MessageDigest messageDigest;
        try{
            messageDigest = MessageDigest.getInstance("SHA-256");
            messageDigest.update(oldName.substring(0, oldName.indexOf(".")).getBytes());
            String newName = byte2Hex(messageDigest.digest()) + oldName.substring(oldName.indexOf("."));
            File storeFile = new File(file, newName);
            uploadFile.transferTo(storeFile);
            InputStream in = new FileInputStream(storeFile);
            String prefix = oldName.substring(oldName.indexOf("."), oldName.length());
            if(prefix.equals(".ipa")){
                filePath = "/iTunes";
            }else if(prefix.equals(".macho")){
                filePath = "/MARSRESCAN";
            }else{
                return "/wrong.html";
            }
            boolean res = FTPUtil.uploadFile(host, port, userName, password, basePath, filePath, newName, in);
            boolean delete = storeFile.delete();
            if(res && delete){
                return "/success.html";
            }
        }catch (Exception e){
            e.printStackTrace();
        }
        return "/wrong.html";
    }

    private String byte2Hex(byte[] bytes) {
        StringBuffer stringBuffer = new StringBuffer();
        String temp = "";
        for (int i = 0; i < bytes.length; i++) {
            temp = Integer.toHexString(bytes[i] & 0XFF);
            if(temp.length() == 1){
                stringBuffer.append("0");
            }
            stringBuffer.append(temp);
        }
        return stringBuffer.toString();
    }

}

FTPUtil

用来连接ftp服务器 上传文件。
具体测试的时候可以在自己本机搭建一个ftp server 百度有教程
basePath 服务器的根目录
filePath 文件的存放文件夹

package com.example.demo.util;

import org.apache.commons.net.ftp.FTP;
import org.apache.commons.net.ftp.FTPClient;
import java.io.IOException;
import java.io.InputStream;

public class FTPUtil {

    public static boolean uploadFile(String host, int port, String username, String password, String basePath,
                                     String filePath, String filename, InputStream input) {
        boolean result = false;
        FTPClient ftp = new FTPClient();
        try {
            int reply;
            ftp.connect(host, port);
            ftp.login(username, password);
            if (!ftp.changeWorkingDirectory(basePath+filePath)) {
                //如果目录不存在创建目录
                String[] dirs = filePath.split("/");
                String tempPath = basePath;
                for (String dir : dirs) {
                    if (null == dir || "".equals(dir)) continue;
                    tempPath += "/" + dir;
                    if (!ftp.changeWorkingDirectory(tempPath)) {
                        if (!ftp.makeDirectory(tempPath)) {
                            return result;
                        } else {
                            ftp.changeWorkingDirectory(tempPath);
                        }
                    }
                }
            }
            //设置上传文件的类型为二进制类型
            ftp.setFileType(FTP.BINARY_FILE_TYPE);
            //上传文件
            if (!ftp.storeFile(filename, input)) {
                return result;
            }
            input.close();
            ftp.logout();
            result = true;
        } catch (IOException e) {
            e.printStackTrace();
        } finally {
            if (ftp.isConnected()) {
                try {
                    ftp.disconnect();
                } catch (IOException ioe) {
                }
            }
        }
        return result;
    }
}

4 重要的配置文件

server:
  port: 8088
spring:
  resources:
    static-locations: classpath:/templates
  servlet:
    multipart:
      max-file-size: 200MB
      max-request-size: 200MB
upload:
  host: 10.64.167.95
  port: 21
  userName: 
  password: 
  basePath: /

总结

实现文件的上传遇到两个坑
1 html与controller之间的调用:
刚开始发现请求app/upload无法相应 后来发现是IDEA的默认端口号是63342 html请求时用的不是80
将IDEA的默认端口号改过来就行了
2 这个坑没法记录 苹果的catlinna系统似乎在读取本地存储文件上需要特殊设置 后来在win上开发就没问题了

你可能感兴趣的:(最完整HTML+springboot实现本地上传文件到ftp服务器)