将图像上传到ASP.net和C#中的文件夹

时间:2018-10-27 23:19:49

标签: asp.net asp.net-mvc

我在StackOverflow上尝试过各种答案,但是都没有解决问题。我正在尝试通过文件类型将图像上传到名为Images的文件夹。问题是它总是在try / catch中命中。我下面有代码块,但删除了安全性凭证。请帮忙!

[HttpPost]
public ActionResult UploadPhoto(HttpPostedFileBase file)
{
    string http = "https://serverName";
    string httpFolder = "/Images";
    byte[] fileBytes = null;

    string fileName = Path.GetFileName(file.FileName);
    using (StreamReader fileStream = new StreamReader(file.InputStream))
    {
        fileBytes = Encoding.UTF8.GetBytes(fileStream.ReadToEnd());
        fileStream.Close();
    }

    try
    {
        FtpWebRequest request = (FtpWebRequest)WebRequest.Create(http + httpFolder + fileName);
        request.Method = WebRequestMethods.Ftp.UploadFile;

        request.Credentials = new NetworkCredential("username", "password"); 
        request.ContentLength = fileBytes.Length;
        request.UsePassive = true;
        request.UseBinary = true;
        request.ServicePoint.ConnectionLimit = fileBytes.Length;
        request.EnableSsl = false;

        using (Stream requestStream = request.GetRequestStream())
        {
            requestStream.Write(fileBytes, 0, fileBytes.Length);
            requestStream.Close();
        }

        FtpWebResponse response = (FtpWebResponse)request.GetResponse();


        response.Close();
        ViewBag.FileUploaded = "File uploaded succesfully!"; 
    }
    catch (WebException ex)
    {

        throw new Exception((ex.Response as FtpWebResponse).StatusDescription);
    }

    return RedirectToAction("UploadPhoto");
}

0 个答案:

没有答案