使用文件路径上传文件作为c#中的字符串

时间:2015-05-01 03:41:42

标签: c# asp.net asp.net-mvc c#-5.0

我的c#代码中的本地机器文件路径仅为字符串,我想从路径中获取文件详细信息,并希望将该文件上载到服务器/应用程序文件夹中。

路径如:

  

C:\用户\ ADMIN \桌面\ Image.png

你能帮我解决一下这个问题吗?

1 个答案:

答案 0 :(得分:2)

文件处理对我来说都是相当新的,但这就是我在最近的MVC项目中所做的。

<强> ImageController: 这就是我保存文件的方式

public ActionResult Create(FormCollection collection)
{
    if (ModelState.IsValid)
    {
        HttpPostedFileBase file = Request.Files["userUploadedFile"];

        var userName = User.Identity.Name;
        var selectAlbum = Request.Form["lstAlbums"];

        Image img = new Image();
        img.FileName = file.FileName;
        img.FileType = file.ContentType;
        img.Size = file.ContentLength;
        img.Path = "/uploads/"; //  + userName

        string relativePath = img.Path + img.FileName;
        // relativePath.Replace("/", "\\"); 
        string absolutePath = Server.MapPath(relativePath); 
        file.SaveAs(absolutePath);
        img.Path = relativePath;
        img.User = User;

        db.Images.Add(img);
        db.SaveChanges();

        return RedirectToAction("Index");
    }

    return RedirectToAction("Create");
}

PostController:这就是我获取图片的方式:

private ApplicationDbContext db = new ApplicationDbContext();

public ActionResult ViewPost(int? id = 1) 
{              
    if (id == null)
    {
         return new HttpStatusCodeResult(HttpStatusCode.BadRequest);
    }
    else 
        {
            Post post = db.Posts.Find(id);
            return View(post);
        }

   }

ViewPost.cshtml 这是我的观点

@model IEnumerable<BlogEngine.Models.Post>


<table class="table">

@foreach (var item in Model) {
    <tr>
        <td>
            @*@Html.ActionLink("About this Website", "About")*@
            <a href="/posts/viewpost/?id=@item.Id">@Html.DisplayFor(modelItem => item.Title)</a>
        </td>
        <td>
            @Html.DisplayFor(modelItem => item.IntroText)
        </td>
        <td>
            @Html.Raw(item.Body)
        </td>
        <td>
            @Html.DisplayFor(modelItem => item.Created)
        </td>
        <td>
            @Html.DisplayFor(modelItem => item.Modified)
        </td>
        <td>
            @Html.DisplayFor(modelItem => item.Author)
        </td>
        <td>
        </td>
    </tr>
}

</table>

根据评论进行更新:

试试这个来获取文件:

try
    {
        Bitmap image1 = (Bitmap) Image.FromFile(@"C:\Documents and Settings\" +
            @"All Users\Documents\My Music\music.bmp", true);

        TextureBrush texture = new TextureBrush(image1);
        texture.WrapMode = System.Drawing.Drawing2D.WrapMode.Tile;
        Graphics formGraphics = this.CreateGraphics();
        formGraphics.FillEllipse(texture, 
            new RectangleF(90.0F, 110.0F, 100, 100));
        formGraphics.Dispose();

    }
    catch(System.IO.FileNotFoundException)
    {
        MessageBox.Show("There was an error opening the bitmap." +
            "Please check the path.");
    }

source