c# - Cannot access a closed file when uploading to memory stream -
i trying create controller allow me save images database. far have bit of code:
/// <summary> /// handles upload /// </summary> /// <returns></returns> [httppost] [route("")] public async task<ihttpactionresult> upload() { // if request not of multipart content, return bad request if (!request.content.ismimemultipartcontent()) return badrequest("your form must of type multipartcontent."); // our provider var provider = new multipartformdatastreamprovider(configurationmanager.appsettings["uploadfolder"]); // upload our file await request.content.readasmultipartasync(provider); // our file var file = provider.contents.first(); var bytes = await file.readasbytearrayasync(); // using memorystream using (var stream = new memorystream(bytes)) { stream.seek(0, seekorigin.begin); // create data var data = "data:image/gif;base64," + convert.tobase64string(stream.toarray()); // return data return ok(data); } }
but isn't working. when using block error message:
"error while copying content stream."
"cannot access closed file."
does know why?
the reason happening multipartformdatastreamprovider closes , disposes uploaded files streams after has written uploaded data file location provided when passed constructor: configurationmanager.appsettings["uploadfolder"]
to access files have been uploaded need consult file data on disk uploaded file location:
so in example code needs use this:
// read first file file data collection: var fileupload = provider.filedata.first; // temp name , path multipartformdatastreamprovider used save file as: var temppath = fileupload.localfilename; // read file's data temp location. var bytes = file.readallbytes(temppath);
additionally if using small files can instead use:
this stores file data in memory , should work expected. warned though if using large files (25mb+) wise stream disk first otherwise might out of memory exceptions .net tries hold whole file in memory.
Comments
Post a Comment