2016-11-11 17 views
0

Ich habe einige Daten in einer Datenbank zu speichern. Ich habe eine Web-API-Post-Methode erstellt, um Daten zu speichern. Im Anschluss ist meine post-Methode:Web API Dateien hochladen

[Route("PostRequirementTypeProcessing")] 
    public IEnumerable<NPAAddRequirementTypeProcessing> PostRequirementTypeProcessing(mdlAddAddRequirementTypeProcessing requTypeProcess) 
    { 
     mdlAddAddRequirementTypeProcessing rTyeProcessing = new mdlAddAddRequirementTypeProcessing(); 

     rTyeProcessing.szDescription = requTypeProcess.szDescription; 
     rTyeProcessing.iRequirementTypeId = requTypeProcess.iRequirementTypeId; 
     rTyeProcessing.szRequirementNumber = requTypeProcess.szRequirementNumber; 
     rTyeProcessing.szRequirementIssuer = requTypeProcess.szRequirementIssuer; 
     rTyeProcessing.szOrganization = requTypeProcess.szOrganization; 
     rTyeProcessing.dIssuedate = requTypeProcess.dIssuedate; 
     rTyeProcessing.dExpirydate = requTypeProcess.dExpirydate; 
     rTyeProcessing.szSignedBy = requTypeProcess.szSignedBy; 
     rTyeProcessing.szAttachedDocumentNo = requTypeProcess.szAttachedDocumentNo; 
     if (String.IsNullOrEmpty(rTyeProcessing.szAttachedDocumentNo)) 
     { 

     } 
     else 
     { 
      UploadFile(); 
     } 
     rTyeProcessing.szSubject = requTypeProcess.szSubject; 
     rTyeProcessing.iApplicationDetailsId = requTypeProcess.iApplicationDetailsId; 
     rTyeProcessing.iEmpId = requTypeProcess.iEmpId; 

     NPAEntities context = new NPAEntities(); 
     Log.Debug("PostRequirementTypeProcessing Request traced"); 

     var newRTP = context.NPAAddRequirementTypeProcessing(requTypeProcess.szDescription, requTypeProcess.iRequirementTypeId, 
            requTypeProcess.szRequirementNumber, requTypeProcess.szRequirementIssuer, requTypeProcess.szOrganization, 
            requTypeProcess.dIssuedate, requTypeProcess.dExpirydate, requTypeProcess.szSignedBy, 
            requTypeProcess.szAttachedDocumentNo, requTypeProcess.szSubject, requTypeProcess.iApplicationDetailsId, 
            requTypeProcess.iEmpId); 

     return newRTP.ToList(); 
    } 

Es gibt ein Feld ‚szAttachedDocumentNo‘ genannt, das ein Dokument, das auch in der Datenbank gespeichert ist wird.

Nach dem Speichern aller Daten möchte ich die physische Datei der 'szAttachedDocumentNo' auf dem Server gespeichert werden. Also habe ich eine Methode namens „Upload“ wie folgt:

[HttpPost] 
    public void UploadFile() 
    { 
     if (HttpContext.Current.Request.Files.AllKeys.Any()) 
     { 
      // Get the uploaded file from the Files collection 
      var httpPostedFile = HttpContext.Current.Request.Files["UploadedFile"]; 

      if (httpPostedFile != null) 
      { 
       // Validate the uploaded image(optional) 
       string folderPath = HttpContext.Current.Server.MapPath("~/UploadedFiles"); 
       //string folderPath1 = Convert.ToString(ConfigurationManager.AppSettings["DocPath"]); 

       //Directory not exists then create new directory 
       if (!Directory.Exists(folderPath)) 
       { 
        Directory.CreateDirectory(folderPath); 
       } 

       // Get the complete file path 
       var fileSavePath = Path.Combine(folderPath, httpPostedFile.FileName); 

       // Save the uploaded file to "UploadedFiles" folder 
       httpPostedFile.SaveAs(fileSavePath); 
      } 
     } 
    } 

Bevor das Projekt läuft, ich die Post-Methode debbugged, so, wenn es um „Upload“ Linie kommt, es nimmt mich in seine Methode. Von der Dateizeile übersprang es die restlichen Zeilen und ging zur letzten Zeile; was bedeutet, dass es keine Datei gesehen hat. Ich bin in der Lage, alles in der Datenbank zu speichern, nur dass ich die physische Datei am angegebenen Speicherort nicht sah. Jede Hilfe würde sehr geschätzt werden.

Grüße,

Somad

Antwort

0

Stellt sicher, dass die Anforderung "content-type": "multipart/form-data" gesetzt ist

  [HttpPost()] 
      public async Task<IHttpActionResult> UploadFile() 
      { 
       if (!Request.Content.IsMimeMultipartContent()) 
        throw new HttpResponseException(HttpStatusCode.UnsupportedMediaType); 

       try 
       { 
        MultipartMemoryStreamProvider provider = new MultipartMemoryStreamProvider(); 

        await Request.Content.ReadAsMultipartAsync(provider); 

        if (provider.Contents != null && provider.Contents.Count == 0) 
        { 
         return BadRequest("No files provided."); 
        } 

        foreach (HttpContent file in provider.Contents) 
        { 
         string filename = file.Headers.ContentDisposition.FileName.Trim('\"'); 

         byte[] buffer = await file.ReadAsByteArrayAsync(); 

         using (MemoryStream stream = new MemoryStream(buffer)) 
         { 
          // save the file whereever you want 

         } 
        } 

        return Ok("files Uploded"); 
       } 
       catch (Exception ex) 
       { 
        return InternalServerError(ex); 
       } 
      } 
Verwandte Themen