Send file from one server to another

Asked

Viewed 2,093 times

3

The application is on an X server. From a precise upload file the file is sent to a Y server. However, I can’t find any 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();
    }
  • Ideally X would provide a Action of Controller be a FileResult, and Y has another Action using a HttpClient. I’ll think of something.

  • 1

    The problem is that Y cannot have any application. It would only provide a directory.

  • the directory is accessible by explorer? for example servor2 Docs, already tried to use only File.WriteAllBytes("\\servidor2\docs\teste.txt") ?;

  • In web Forms I could do like this: string ftpAddres = "ftp://" + username + ":" + ftpPass + "@" + ftpserver + "/" + name; using (var Webclient = new System.Net.Webclient()) { Webclient.Proxy = null; Webclient.Uploaddata(new Uri(ftpAddres), file.Filebytes); }

  • You need to necessarily access an FTP directory?

  • Yes. Because it is an external server (UOL)

Show 1 more comment

2 answers

2


If the server will 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();
    }
  • Completelocalpath, would be what? And in Return true, is giving error!

  • Let me give you a translation.

  • And where Httppostedfilebase file would enter?

  • So, this answer is for a File Download. I’ll put the Upload. Perai.

  • @Diegozanardo Now I think you have everything you need.

  • It is giving error exactly where I have doubts. File.Openread(Completepath). Instead of Completepath it would be for example "255.255.255.1/root/"?

  • @Diegozanardo ftp://oenderecodouol/root

Show 2 more comments

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 and I’ll improve the answer.

  • On the Y site I cannot have an application. Only the folder.

  • 1

    You can get access to the directory but you can’t run an application inside, right? Would it by any chance be a limit of the hosting plan? You cannot add the above lines to a separate project page that is already running?

  • Exactly @Rafaelbarbosa

  • I’ll put another answer to that scenario.

Browser other questions tagged

You are not signed in. Login or sign up in order to post.