공부/C#

C# FTP 이미지업로드

딸기버블티 2022. 5. 6. 14:59
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
for (int i = startIndex; i <= page; i++)
{
    MakeDirectory("ftp://ftp.ftp주소/"); //경로 검사 후 경로 생성
    Thread.Sleep(int.Parse(TimeSpan.FromSeconds(2).TotalMilliseconds.ToString())); //2초 쉬기
    imageDt;
    Parallel.ForEach(imageDt.AsEnumerable(), row => //병렬로 처리
    {
        string extension = Path.GetExtension(url); //이미지 확장자 구하기(.jpg나 .png)
        
        string 업로드할이미지경로= string.Empty;//업로드될 ftp경로 및 이름
        string 원본이미지url= string.Empty;//업로드할 url(이미지링크)
        업로드할이미지경로= "" + extension; 
        
        result = UploadFileList(원본이미지url, 업로드할이미지경로);
        results.Add(result);
    });
}
 
// 업로드 함수
private UploadImageResult UploadFileList(string imageUrl, string ftpPath)
{
    string returnUrl = "https://ftp주소/";
    returnUrl = returnUrl + ftpPath;//업로드되고 업로드 된 ftp의 경로
    try
    {
        
        string ftpUrl = string.Empty;
        ftpUrl = "ftp://ftp.ftp주소/" + ftpPath;
 
        FtpWebRequest req = Connect(ftpUrl);
        byte[] buffer = new byte[0];
        buffer = 이미지 바이트;
        using (var ftpStream = req.GetRequestStream())
        {
            ftpStream.Write(buffer, 0, buffer.Length);
        }
 
        // 응답 표시
        using (var resp = (FtpWebResponse)req.GetResponse())
        {
            if (resp.StatusCode == FtpStatusCode.ClosingData)//성공
            {
                
            }
            else
            {
                throw new Exception("FTP 업로드 실패");
            }
        }
 
        return result;
 
    }
    catch(Exception ex)
    {
        
    }
 
    return result ;
}
 
//FTP연결 함수
private FtpWebRequest Connect(string ftpUrl)
{
    FtpWebRequest req = (FtpWebRequest)WebRequest.Create(ftpUrl);
    req.KeepAlive = true;
    req.Method = WebRequestMethods.Ftp.UploadFile;
    req.Credentials = new NetworkCredential("ftp아이디""ftp비밀번호");
    req.UsePassive = true;
    return req;
}
 
//경로검사 후 경로없으면 디렉터리 생성
private void MakeDirectory(string directory)
{
    FtpWebRequest req = Connect(directory);
 
    req.Method = WebRequestMethods.Ftp.ListDirectory;
    try
    {
        using (var result = (FtpWebResponse)req.GetResponse())
        {
            return;
        }
    }
    catch
    {
        req = Connect(directory);
        req.Method = WebRequestMethods.Ftp.MakeDirectory;
        using (var resp = (FtpWebResponse)req.GetResponse())
        {
            Console.WriteLine(resp.StatusCode);
        }
    }
}
 
cs