最完整HTML+springboot實(shí)現(xiàn)本地上傳文件到ftp服務(wù)器

1搭建環(huán)境

IDEA+ windows10

image.png

2HTML頁面

upload.html

<!DOCTYPE html>
<html xmlns: th="http://www.thymeleaf.org">
<head>
    <meta charset="UTF-8">
    <title>Title</title>
</head>
<body>
    <form action="/app/upload" method="post" enctype="multipart/form-data">
        選擇文件 <input type="file" name="uploadFile"/><br/>
        <input type="submit" name="上傳"/><br/>
    </form>

</body>
</html>

success.html

<!DOCTYPE html>
<html xmlns: th="http://www.thymeleaf.org">
<head>
    <meta charset="UTF-8">
    <title>上傳成功</title>
</head>
<body>
    文件上傳成功!
    <button onclick="window.location.href = '/upload.html'">繼續(xù)添加</button>
</body>
</html>

wrong.html

<!DOCTYPE html>
<html xmlns: th="http://www.thymeleaf.org">
<head>
    <meta charset="UTF-8">
    <title>錯(cuò)誤</title>
</head>
<body>
    文件上傳失?。?  <button onclick="window.location.href = '/upload.html'">繼續(xù)添加</button>
</body>
</html>

3 Controller 獲取html上傳的multipartfile

controller 接受html傳來的文件后 先將該文件存放在本地tomcat某目錄下(具體可以自行打印文件的路徑查看)。
然后讀取本地文件的路徑和文件名(文件名經(jīng)過了sha256加密) 新建輸入流
調(diào)用FTPUtil的上傳接口 上傳 到服務(wù)器上同時(shí)刪除本地的緩存文件
上傳成功則跳轉(zhuǎn)success界面可繼續(xù)添加
否則進(jìn)入wrong界面
ps:本例中只針對(duì)ipa 和mount文件進(jìn)行上傳

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服務(wù)器 上傳文件。
具體測試的時(shí)候可以在自己本機(jī)搭建一個(gè)ftp server 百度有教程
basePath 服務(wù)器的根目錄
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)) {
                //如果目錄不存在創(chuàng)建目錄
                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);
                        }
                    }
                }
            }
            //設(shè)置上傳文件的類型為二進(jìn)制類型
            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: /

總結(jié)

實(shí)現(xiàn)文件的上傳遇到兩個(gè)坑
1 html與controller之間的調(diào)用:
剛開始發(fā)現(xiàn)請(qǐng)求app/upload無法相應(yīng) 后來發(fā)現(xiàn)是IDEA的默認(rèn)端口號(hào)是63342 html請(qǐng)求時(shí)用的不是80
將IDEA的默認(rèn)端口號(hào)改過來就行了
2 這個(gè)坑沒法記錄 蘋果的catlinna系統(tǒng)似乎在讀取本地存儲(chǔ)文件上需要特殊設(shè)置 后來在win上開發(fā)就沒問題了

?著作權(quán)歸作者所有,轉(zhuǎn)載或內(nèi)容合作請(qǐng)聯(lián)系作者
【社區(qū)內(nèi)容提示】社區(qū)部分內(nèi)容疑似由AI輔助生成,瀏覽時(shí)請(qǐng)結(jié)合常識(shí)與多方信息審慎甄別。
平臺(tái)聲明:文章內(nèi)容(如有圖片或視頻亦包括在內(nèi))由作者上傳并發(fā)布,文章內(nèi)容僅代表作者本人觀點(diǎn),簡書系信息發(fā)布平臺(tái),僅提供信息存儲(chǔ)服務(wù)。

相關(guān)閱讀更多精彩內(nèi)容

友情鏈接更多精彩內(nèi)容