How to get more information from a InputStremed file?
If I'm using the InputStream
to receive a file, like
HttpContext.Current.Request.InputStream
How can get more information about the file?
I can easily convert a Stream into a phisical File, but for example, how would I know the file extension in use?
string fileIn = @"C:\Temp\inputStreamedFile.xxx"; // What extension?
using (FileStream fs = System.IO.File.Create(fileIn))
{
Stream f = HttpContext.Current.Request.InputStream;
byte[] bytes = new byte[f.Length];
f.Read(bytes, 0, (int)f.Length);
fs.Write(bytes, 0, bytes.Length);
}
The idea behind this is because using HttpPostedFileBase
I always get null:
public ContentResult Send(HttpPostedFileBase fileToUpload, string email)
{
// Get file stream and save it
// Get File in stream
string fileIn = Path.Combine(uploadsPath, uniqueIdentifier),
fileOut = Path.Combine(convertedPath, uniqueIdentifier + ".pdf");
// Verify that the us开发者_Python百科er selected a file
if (fileToUpload != null && fileToUpload.ContentLength > 0)
{
// extract only the fielname
string fileExtension = Path.GetExtension(fileToUpload.FileName);
fileIn = String.Concat(fileIn, fileExtension);
fileToUpload.SaveAs(fileIn);
}
// TODO: Add Convert File to Batch
return Content("File queued for process with id: " + uniqueIdentifier);
}
and this is what I'm sending from the command line:
$ curl --form email='mail@domain.com' --form fileToUpload='C:\temp\MyWord.docx' http://localhost:64705/send/
File queued for process with id: 1d777cc7-7c08-460c-8412-ddab72408123
the variable email
is filled up correctly, but fileToUpload
is always null.
P.S. This does not happen if I use a form to upload the same data.
I'm sorry if this doesn't help, but why use InputStream to get uploaded file(s) ?
This is what I usually do:
[HttpPost]
public ActionResult Upload(HttpPostedFileBase[] files) {
String physicalPath = "c:\\whatever";
foreach (var file in files) {
String extension = Path.GetExtension(file.FileName);
file.SaveAs(physicalPath + "\\" + file.FileName);
}
return View();
}
The only problem I found was using curl... I was forgetting the @
sign that mention that the uploaded form would be encoded as multipart/form-data
.
The correct curl command to use HttpPostedFileBase
would be:
$ curl --form email='mail@domain.com'
--form fileToUpload=@'C:\temp\MyWord.docx'
http://localhost:64705/send/
You can get the info about posted file from <input type="file" />
. But actually it's used a bit different way to upload files in asp.net mvc check out here
精彩评论