簡體   English   中英

如何在FileUpload控件Asp.net中重命名文件?

[英]How to rename File in FileUpload Control Asp.net?

我的方法帶有上傳的圖像,我需要將其重命名為我的應用程序中的固定名稱但是當使用File.Copy方法時它返回結果(文件不存在)我不知道怎么回事

我試過這個File.Copy(UploadFile.FileName,newFilName); 也沒有回應

 string filename = Path.GetFileName(FileUpload.FileName);
                string extension = Path.GetExtension(FileUpload.PostedFile.FileName);

                string oldFileName = FileUpload.FileName;
                string newFileName = ("aboutusImage" + extension);

                File.Copy(oldFileName, newFileName);
                File.Delete(oldFileName);

                File.Move(FileUpload.FileName, newFileName);
                FileUpload.SaveAs(Server.MapPath("~/Styles/aboutusImages/") + newFileName);

                var updateAboutus = (from a in dbContext.DynamicText
                                     where a.Id == 1
                                     select a).Single();
                updateAboutus.Id = updateAboutus.Id;
                updateAboutus.Name = updateAboutus.Name;
                updateAboutus.Image = Path.Combine("~/Styles/aboutusImages/", "aboutusImage.jpg");

                dbContext.SaveChanges();

FileUpload.FileName屬性表示客戶端計算機上的文件名,而不是服務器上的文件名。 嘗試使用File.Copy幾乎沒有成功的可能性,除非您在當前文件夾中的自己的服務器中具有相同的文件。

MSDN示例

protected void UploadButton_Click(object sender, EventArgs e)
{
    // Specify the path on the server to
    // save the uploaded file to.
    String savePath = @"c:\temp\uploads\";

    // Before attempting to perform operations
    // on the file, verify that the FileUpload 
    // control contains a file.
    if (FileUpload1.HasFile)
    {

      String fileName = FileUpload1.FileName;

      // Append the name of the file to upload to the path.
      savePath += fileName;


      // Call the SaveAs method to save the 
      // uploaded file to the specified path.
      // This example does not perform all
      // the necessary error checking.               
      // If a file with the same name
      // already exists in the specified path,  
      // the uploaded file overwrites it.
      FileUpload1.SaveAs(savePath);

當然,以下File.Delete,File.Move有同樣的問題,應該刪除

您嘗試移動的名稱只是客戶端上給出的名稱,而不是服務器上的當前名稱。 它可能位於服務器上的某個臨時位置。

您可能需要FileUpload.SaveAs函數。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM