最完整HTML+springboot實現(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>錯誤</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ù)器上同時刪除本地的緩存文件
上傳成功則跳轉(zhuǎn)success界面可繼續(xù)添加
否則進入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服務(wù)器 上傳文件麻捻。
具體測試的時候可以在自己本機搭建一個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è)置上傳文件的類型為二進制類型
            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é)

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

?著作權(quán)歸作者所有,轉(zhuǎn)載或內(nèi)容合作請聯(lián)系作者
  • 序言:七十年代末饺藤,一起剝皮案震驚了整個濱河市哭尝,隨后出現(xiàn)的幾起案子驹吮,更是在濱河造成了極大的恐慌,老刑警劉巖逐抑,帶你破解...
    沈念sama閱讀 218,036評論 6 506
  • 序言:濱河連續(xù)發(fā)生了三起死亡事件鸠儿,死亡現(xiàn)場離奇詭異屹蚊,居然都是意外死亡厕氨,警方通過查閱死者的電腦和手機,發(fā)現(xiàn)死者居然都...
    沈念sama閱讀 93,046評論 3 395
  • 文/潘曉璐 我一進店門汹粤,熙熙樓的掌柜王于貴愁眉苦臉地迎上來命斧,“玉大人,你說我怎么就攤上這事嘱兼」幔” “怎么了?”我有些...
    開封第一講書人閱讀 164,411評論 0 354
  • 文/不壞的土叔 我叫張陵芹壕,是天一觀的道長汇四。 經(jīng)常有香客問我,道長踢涌,這世上最難降的妖魔是什么通孽? 我笑而不...
    開封第一講書人閱讀 58,622評論 1 293
  • 正文 為了忘掉前任,我火速辦了婚禮睁壁,結(jié)果婚禮上背苦,老公的妹妹穿的比我還像新娘互捌。我一直安慰自己,他們只是感情好行剂,可當(dāng)我...
    茶點故事閱讀 67,661評論 6 392
  • 文/花漫 我一把揭開白布秕噪。 她就那樣靜靜地躺著,像睡著了一般厚宰。 火紅的嫁衣襯著肌膚如雪腌巾。 梳的紋絲不亂的頭發(fā)上,一...
    開封第一講書人閱讀 51,521評論 1 304
  • 那天铲觉,我揣著相機與錄音壤躲,去河邊找鬼。 笑死备燃,一個胖子當(dāng)著我的面吹牛碉克,可吹牛的內(nèi)容都是我干的。 我是一名探鬼主播并齐,決...
    沈念sama閱讀 40,288評論 3 418
  • 文/蒼蘭香墨 我猛地睜開眼漏麦,長吁一口氣:“原來是場噩夢啊……” “哼!你這毒婦竟也來了况褪?” 一聲冷哼從身側(cè)響起撕贞,我...
    開封第一講書人閱讀 39,200評論 0 276
  • 序言:老撾萬榮一對情侶失蹤,失蹤者是張志新(化名)和其女友劉穎测垛,沒想到半個月后捏膨,有當(dāng)?shù)厝嗽跇淞掷锇l(fā)現(xiàn)了一具尸體,經(jīng)...
    沈念sama閱讀 45,644評論 1 314
  • 正文 獨居荒郊野嶺守林人離奇死亡食侮,尸身上長有42處帶血的膿包…… 初始之章·張勛 以下內(nèi)容為張勛視角 年9月15日...
    茶點故事閱讀 37,837評論 3 336
  • 正文 我和宋清朗相戀三年号涯,在試婚紗的時候發(fā)現(xiàn)自己被綠了。 大學(xué)時的朋友給我發(fā)了我未婚夫和他白月光在一起吃飯的照片锯七。...
    茶點故事閱讀 39,953評論 1 348
  • 序言:一個原本活蹦亂跳的男人離奇死亡链快,死狀恐怖,靈堂內(nèi)的尸體忽然破棺而出眉尸,到底是詐尸還是另有隱情域蜗,我是刑警寧澤,帶...
    沈念sama閱讀 35,673評論 5 346
  • 正文 年R本政府宣布噪猾,位于F島的核電站霉祸,受9級特大地震影響,放射性物質(zhì)發(fā)生泄漏袱蜡。R本人自食惡果不足惜丝蹭,卻給世界環(huán)境...
    茶點故事閱讀 41,281評論 3 329
  • 文/蒙蒙 一、第九天 我趴在偏房一處隱蔽的房頂上張望戒劫。 院中可真熱鬧半夷,春花似錦婆廊、人聲如沸。這莊子的主人今日做“春日...
    開封第一講書人閱讀 31,889評論 0 22
  • 文/蒼蘭香墨 我抬頭看了看天上的太陽。三九已至湘换,卻和暖如春宾舅,著一層夾襖步出監(jiān)牢的瞬間,已是汗流浹背彩倚。 一陣腳步聲響...
    開封第一講書人閱讀 33,011評論 1 269
  • 我被黑心中介騙來泰國打工筹我, 沒想到剛下飛機就差點兒被人妖公主榨干…… 1. 我叫王不留,地道東北人帆离。 一個月前我還...
    沈念sama閱讀 48,119評論 3 370
  • 正文 我出身青樓蔬蕊,卻偏偏與公主長得像,于是被迫代替她去往敵國和親哥谷。 傳聞我的和親對象是個殘疾皇子岸夯,可洞房花燭夜當(dāng)晚...
    茶點故事閱讀 44,901評論 2 355

推薦閱讀更多精彩內(nèi)容