Пример #1
0
        public async Task <HttpResponseMessage <FileList> > PostFormData( )
        {
            //TODO: store the original filename along with the file.

            if (!Request.Content.IsMimeMultipartContent( ))
            {
                throw new HttpResponseException(HttpStatusCode.UnsupportedMediaType);
            }

            var provider = new LocalCacheStreamProvider( );

            try
            {
                await Request.Content.ReadAsMultipartAsync(provider);
            }
            catch (Exception ex)
            {
                throw new WebArgumentException(string.Format("Invalid file upload request. Request: {0}", Request), ex);
            }

            var idMap = new FileList( );

            try
            {
                string expectedType = Request.RequestUri.ParseQueryString( )["type"];

                foreach (var entry in provider.RemoteToLocalFileNameMap)
                {
                    string remoteFileName = entry.Key;
                    string localFileName  = entry.Value;

                    string token;

                    if (!FileRepositoryHelper.CheckFileExtensionIsValid(remoteFileName, expectedType))
                    {
                        throw new PlatformSecurityException("Disallowed file type.");
                    }

                    using (var source = new FileStream(localFileName, FileMode.Open, FileAccess.Read, FileShare.Read))
                    {
                        token = FileRepositoryHelper.AddTemporaryFile(source);
                    }
                    idMap.Add(new FileListItem
                    {
                        FileName = remoteFileName, Hash = token
                    });
                }
            }
            finally
            {
                // clean up the local files
                foreach (var entry in provider.RemoteToLocalFileNameMap)
                {
                    File.Delete(entry.Value);
                }
            }


            return(new HttpResponseMessage <FileList>(idMap));
        }