I can use multipart/form-data
to upload a File, But i can't find any tutorials about multipart/form-data
upload a Folder.
This is my code upload a file:
html:
<form name="form1" method="post" enctype="multipart/form-data" action="api/upload">
<fieldset>
<legend>File Upload Example</legend>
<div>
<label for="caption">Image Caption</label>
<input name="caption" type="text" />
</div>
<div>
<label for="image1">Image File</label>
<input name="image1" type="file" />
</div>
<div>
<input type="submit" value="Submit" />
</div>
</fieldset>
</form>
Controller:
public class UploadController : ApiController
{
[AcceptVerbs("GET", "POST")]
public async Task<HttpResponseMessage> PostFile()
{
// Check if the request contains multipart/form-data.
if (!Request.Content.IsMimeMultipartContent())
{
throw new HttpResponseException(HttpStatusCode.UnsupportedMediaType);
}
string root = HttpContext.Current.Server.MapPath("~/App_Data");
var provider = new MultipartFormDataStreamProvider(root);
try
{
StringBuilder sb = new StringBuilder(); // Holds the response body
// Read the form data and return an async task.
await Request.Content.ReadAsMultipartAsync(provider);
// This illustrates how to get the file names for uploaded files.
foreach (var file in provider.FileData)
{
var originalFile = file.Headers.ContentDisposition.FileName.TrimStart('"').TrimEnd('"'); ;
FileInfo fileInfo = new FileInfo(file.LocalFileName);
fileInfo.CopyTo(Path.Combine(root, originalFile), true);
sb.Append(string.Format("Uploaded file: {0} ({1} bytes)\n", originalFile, fileInfo.Length));
fileInfo.Delete();
}
return new HttpResponseMessage()
{
Content = new StringContent(sb.ToString())
};
}
catch (System.Exception e)
{
return Request.CreateErrorResponse(HttpStatusCode.InternalServerError, e);
}
}
}
Can I use multipart/form-data
to upload a folder?