Send file from one server to another

3

The application is located on an X server. From a file upload I need the file to be sent to a Y server. But I can not find a solution for this. The application is in MVC asp net. To upload the file to the same server I use:

    [HttpPost]
    public ActionResult Create(HttpPostedFileBase file)
    {          
        if (file == null)
            ModelState.AddModelError("Arquivo", "Arquivo deve ser válido.");
        else
        {
            string nomeArquivo = DateTime.Now.ToLongTimeString().Replace("/", "").Replace(":", "") + file.FileName.Substring(file.FileName.LastIndexOf("."));
            string path = Path.Combine(Server.MapPath("~/arquivos"),
                                       Path.GetFileName(nomeArquivo));
            file.SaveAs(path);
        }
        return View();
    }
    
asked by anonymous 09.06.2014 / 18:31

2 answers

2

If the server is going to download, implement the methods:

public ActionResult DownloadFile()
{
    FtpWebRequest objFTP = null;
    try
    {
        objFTP = FTPDetail("Arquivo.txt");
        objFTP.Method = WebRequestMethods.Ftp.DownloadFile;

        using (FtpWebResponse response = (FtpWebResponse)objFTP.GetResponse())
        {
            using (Stream ftpStream = response.GetResponseStream())
            {
                int contentLen;

                // Não precisa usar necessariamente uma variável. 
                // Pode ser uma String fixa.
                using (FileStream fs = new FileStream(variavelQueApontaOndeOArquivoVaiserSalvo, FileMode.OpenOrCreate))
                {
                    byte[] buff = new byte[2048];
                    contentLen = ftpStream.Read(buff, 0, buff.Length);

                    while (contentLen != 0)
                    {
                        fs.Write(buff, 0, buff.Length);
                        contentLen = ftpStream.Read(buff, 0, buff.Length);
                    }

                    objFTP = null;
                }
            }
        }

        // Aqui você retorna uma View de Sucesso, seu lá como você quer fazer.
        return View();
    }
    catch (Exception Ex)
    {
        if (objFTP!= null)
        {
            objFTP.Abort();
        }

        throw Ex;
    }
}

private FtpWebRequest FTPDetail(string FileName)
{
    string uri = "";
    string serverIp = "255.255.255.1";
    string Username = "usuario";
    string Password = "teste123";
    uri = "ftp://" + serverIp + "/root/" + FileName;

    FtpWebRequest objFTP;
    objFTP = (FtpWebRequest)FtpWebRequest.Create(new Uri(uri));
    objFTP.Credentials = new NetworkCredential(Username, Password);
    objFTP.UsePassive = true;
    objFTP.KeepAlive = false;
    objFTP.Proxy = null;
    objFTP.UseBinary = false;
    objFTP.Timeout = 90000;

    return objFTP;
}

Now, if the server is going to send the files to an FTP server, implement the following:

    [HttpPost]
    public ActionResult Create(HttpPostedFileBase file)
    {          
        if (file == null)
            ModelState.AddModelError("Arquivo", "Arquivo deve ser válido.");
        else
        {
            string nomeArquivo = DateTime.Now.ToLongTimeString().Replace("/", "").Replace(":", "") + file.FileName.Substring(file.FileName.LastIndexOf("."));
            string path = Path.Combine(Server.MapPath("~/arquivos"),
                                       Path.GetFileName(nomeArquivo));
            file.SaveAs(path);
        }

        FtpWebRequest objFTP= null;
        try
        {
            objFTP= FTPDetail(path);
            objFTP.Method = WebRequestMethods.Ftp.UploadFile;
            using (FileStream fs = File.OpenRead(CompletePath))
            {
                byte[] buff = new byte[fs.Length];
                using (Stream strm = objFTP.GetRequestStream())
                {
                    contentLen = fs.Read(buff, 0, buff.Length);

                    while (contentLen != 0)
                    {
                        strm.Write(buff, 0, buff.Length);
                        contentLen = fs.Read(buff, 0, buff.Length);
                    }

                    objFTP = null;
                }
            }

            return true;

        }
        catch (Exception Ex)
        {
            if (objFTP!= null)
            {
                objFTP.Abort();
            }

            throw Ex;
        }

        return View();
    }
    
09.06.2014 / 19:06
1

On site X, implement the following:

public FileResult DownloadArquivo()
{
    // Abra o arquivo e o transforme em um Array de bytes

    return File(bytes, System.Net.Mime.MediaTypeNames.Application.Octet,
            nomeArquivo + "." + extensao);
}

On site Y, implement the following:

public async Task<ActionResult> SuaAcao() {
    var client = new HttpClient();

    var uri = new Uri("http://enderecoDoSiteX/ControllerDeDownload/DownloadArquivo");
    HttpResponseMessage response = await client.GetAsync(uri);

    if (response.IsSuccessStatusCode)
    {
        var bytes = response.Content.ReadAsStreamAsync().Result;
        // Faça aqui a lógica de salvar o arquivo
    }

    // Retorne aqui alguma coisa, se precisar.
    // View(), RedirectToAction(), etc.
}

Give me more information as I improve the answer.

    
09.06.2014 / 18:53