2012-08-06 34 views
-1

我有一個控制器方法,它以HttpPostedFileBase picture作爲參數。當然,它用於從表單加載圖像。但是現在我想使用該方法從另一個方法加載文件。我可以在代碼中使用路徑創建HttpPostedFileBase文件嗎?或者可能是另一種解決方案是首選?如何從asp網絡mvc中的C#代碼發佈文件?

好吧,代碼:

public ActionResult UploadPicture(HttpPostedFileBase picture) 
{ 
    if (picture.ContentLength > Convert.ToInt32(ConfigurationManager.AppSettings["MaxMBFileSize"]) * 1024 * 1024 || picture.ContentLength == 0) 
    { 
     return ClientError(ErrorCodes.ClientErrorCodes.FileSizeError, "File size is incorrect"); 
    } 
    else 
    { 
     string contentType = picture.ContentType; 

     if (!PictureHelper.ContentTypeIsValid(contentType)) 
     { 
      return ClientError(ErrorCodes.ClientErrorCodes.MimeTypeError, "Incorrect file type"); 
     } 
     else 
     { 
      string pictureName = Guid.NewGuid().ToString(); 
      pictureName += picture.FileName.Substring(picture.FileName.LastIndexOf('.')); 

      string serverPath = AppDomain.CurrentDomain.BaseDirectory; 
      picture.SaveAs(serverPath + ConfigurationManager.AppSettings["LocalImagesPath"] + pictureName); 

      return Success(new { pictureName = pictureName }); 
     } 
    } 
} 

真的,身體絕對沒有關係。當然,我有類似:

<form method="post" action="Photo\UploadPicture"> 
    <input type="file"> 
    <input type="submit" value="submit"> 
</form> 

我想是這樣的:

public ActionResult NewMethod() 
{ 
    string path = ""; // real path to file here 
    var file = OhMyGodMagicTransfer(path); 
    // sending request 
    request.attach(file); 
    request.send; 
} 
+1

你說你有一個方法,你想重用它。我想說的答案可能是「肯定,爲什麼不呢?代碼重用是一件好事!」但是你沒有公佈有關該方法的細節,它是如何使用的,以及該方法實際做了什麼,所以不可能說。 – 2012-08-06 09:26:35

+0

當用戶使用表單發佈文件時,它被髮布到帶有HttpPostedFileBase參數的第一個方法。這很明顯。我想在第二種方法中做同樣的事情,就像使用表格一樣。調用第一個方法或者給出一些簡單的參數非常簡單,但我想知道如何給文件參數。創建HttpPostedFileBase對象可能是解決方案,但我不知道它是否真實 – lenden 2012-08-06 09:30:12

+0

對您而言可能是顯而易見的,但對於我們閱讀誰看不到您的代碼的人來說,沒有什麼是顯而易見的。 「文件參數」是什麼意思?你是什​​麼意思「是真的嗎?」 – 2012-08-06 09:32:25

回答

2

如果文件已經保存到磁盤上,然後只返回一個FilePathResult:

public ActionResult FileDownload() 
     { 
      var fileLocation = "C:\file.jpg"; 
      var fileType = "image/jpeg" //this is the Mime content type; 
      return File(fileLocation , fileType); 
     } 

檢查因爲你可以返回文件流或字節數組。

+0

如何在第一種方法中使用它? HttpPostedFileBase圖片=文件(fileLocation,「application/pdf」);不起作用 – lenden 2012-08-06 11:01:18

+0

剛編輯答案。在你的情況下,只需使用'return File(path,「image/jpg」);' 。假設該文件是一個jpg文件或只是將文件類型編輯爲適當的Mime類型,則返回「012」對該案件沒有影響。http://www.webmaster-toolkit.com/mime-types.shtml – Judo 2012-08-06 11:05:35

+0

「return」對案件沒有影響。我需要將我的文件發送到其他網址。在哪裏連接返回? – lenden 2012-08-06 11:09:15