2012-06-27 3 views
0

ASP.NET MVC 3 컨트롤러 동작이 있습니다. 이 동작은 다음과 같이 정의됩니다.WebRequest를 통해 ASP.NET MVC 3 작업으로 데이터 및 파일 업로드

[AcceptVerbs(HttpVerbs.Post)] 
public ActionResult Index(string parameter1, HttpPostedFileBase uploadFile) 
{ 
    if (parameter1 == null) 
    return Json(new { status = "Error" }, JsonRequestBehavior.AllowGet); 

    if (uploadFile.ContentLength == 0) 
    return Json(new { status = "Error" }, JsonRequestBehavior.AllowGet); 

    return Json(new { status = "Success" }, JsonRequestBehavior.AllowGet); 
} 

C# 응용 프로그램을 통해이 끝점에 업로드해야합니다. 현재 다음을 사용하고 있습니다.

public void Upload() 
{ 
    WebRequest request = HttpWebRequest.Create("http://www.mydomain.com/myendpoint"); 
    request.Method = "POST"; 
    request.ContentType = "multipart/form-data"; 
    request.BeginGetRequestStream(new AsyncCallback(UploadBeginGetRequestStreamCallBack), request); 
} 

private void UploadBeginGetRequestStreamCallBack(IAsyncResult ar) 
{ 
    string json = "{\"parameter1\":\"test\"}"; 

    HttpWebRequest webRequest = (HttpWebRequest)(ar.AsyncState); 
    using (Stream postStream = webRequest.EndGetRequestStream(ar)) 
    { 
    byte[] byteArray = Encoding.UTF8.GetBytes(json); 
    postStream.Write(byteArray, 0, byteArray.Length); 
    postStream.Close(); 
    } 
    webRequest.BeginGetResponse(new AsyncCallback(Upload_Completed), webRequest); 
} 

private void Upload_Completed(IAsyncResult result) 
{ 
    WebRequest request = (WebRequest)(result.AsyncState); 
    WebResponse response = request.EndGetResponse(result); 
    // Parse response 
} 

상태가 항상 "오류"입니다. 추가 파기 후, 나는 parameter1이 항상 null임을 알아 차렸다. 나는 약간 혼란스러워. 누군가가 프로그래밍 방식으로 WebRequest를 통해 코드의 파일뿐 아니라 parameter1에 대한 데이터를 보내는 방법을 알려주실 수 있습니까?

감사합니다.

답변

3

야, 이건 힘들었어!

프로그래밍 방식으로 파일을 MVC 작업에 업로드하는 방법을 찾았지만 정말 미안합니다. 찾은 해결책은 파일을 바이트 배열로 변환하고 문자열로 직렬화합니다.

여기에서 살펴보십시오.

이것은 당신의 컨트롤러 액션입니다 :

[AcceptVerbs(HttpVerbs.Post)] 
      public ActionResult uploadFile(string fileName, string fileBytes) 
      { 
       if (string.IsNullOrEmpty(fileName) || string.IsNullOrEmpty(fileBytes)) 
        return Json(new { status = "Error" }, JsonRequestBehavior.AllowGet); 

       string[] byteToConvert = fileBytes.Split('.'); 
       List<byte> fileBytesList = new List<byte>(); 
    byteToConvert.ToList<string>() 
      .Where(x => !string.IsNullOrEmpty(x)) 
      .ToList<string>() 
      .ForEach(x => fileBytesList.Add(Convert.ToByte(x))); 

       //Now you can save the bytes list to a file 

       return Json(new { status = "Success" }, JsonRequestBehavior.AllowGet); 
      } 

그리고 이것은 (파일을 게시)를 클라이언트 코드입니다 : 웹 인터페이스에서 파일 업로드에 관한

public void Upload() 
     { 
      WebRequest request = HttpWebRequest.Create("http://localhost:7267/Search/uploadFile"); 
      request.Method = "POST"; 
      //This is important, MVC uses the content-type to discover the action parameters 
      request.ContentType = "application/x-www-form-urlencoded"; 

      byte[] fileBytes = System.IO.File.ReadAllBytes(@"C:\myFile.jpg"); 

      StringBuilder serializedBytes = new StringBuilder(); 

      //Let's serialize the bytes of your file 
      fileBytes.ToList<byte>().ForEach(x => serializedBytes.AppendFormat("{0}.", Convert.ToUInt32(x))); 

      string postParameters = String.Format("fileName={0}&fileBytes={1}", "myFile.jpg", serializedBytes.ToString()); 

      byte[] postData = Encoding.UTF8.GetBytes(postParameters); 

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

      request.BeginGetResponse(new AsyncCallback(Upload_Completed), request); 
     } 

     private void Upload_Completed(IAsyncResult result) 
     { 
      WebRequest request = (WebRequest)(result.AsyncState); 
      WebResponse response = request.EndGetResponse(result); 
      // Parse response 
     } 

Hanselman has a good post, 그건 네가 아니야.

다시 파일에 바이트 배열을 변환하는 데 도움이 필요한 경우,이 스레드 확인 :이 도움이 Can a Byte[] Array be written to a file in C#?

희망을.

누군가가 더 나은 해결책을 가지고 있다면, 나는 그것에 대해 살펴보고 싶습니다.

안부, Calil

+0

노력 주셔서 너무 감사드립니다. 이상하게도 컨트롤러 액션에서 byteToConvert.ToList가 나타날 때 () .ForEach (x => fileBytesList.Add (Convert.ToByte (x))); "System.FormatException 입력 문자열이 올바른 형식이 아닙니다." –

+0

잠시만 = =) –

+0

야, 정말 미안해. 2 개의 오류가 있습니다 (x가 비어 있는지 확인하지 않고 string.Concat이 아니라 string.Format을 호출). 두 코드 스 니펫이 모두 업데이트되었습니다. –