文件上傳去除"Content-Disposition: form-data"

某個項目中爲了統一處理文件上傳業務,建立了一個FileUpload Handle,因爲上傳客戶端用到各類技術,當時爲了方便斷點續傳,就直接接收請求中的文件內容(多是分片),因此處理的不是規範的http請求,一直工做的很好,可是如今使用html代碼上傳文件時遇到了問題:
服務接收到的文件中會多一個頭和尾,原始內容如:html

Part,Product
1,1
1,2

服務端接收到的如:ajax

-----------------------------7e0bc1790bd2
Content-Disposition: form-data; name="picture"; filename="C:\Users\ns56\Desktop\key_no.csv"
Content-Type: application/vnd.ms-excel

Part,Product
1,1
1,2
-----------------------------7e0bc1790bd2--

因而可知html上傳的是標準http請求,附帶了文件信息,那麼如今要作的就是去掉"Content-Disposition: form-data"
通過分析只能使用Ajax來發送請求:app

    <script>
        function doUpload() {
            $.ajax({
                url: 'http://',
                type: 'POST',
                data: document.getElementById('file1').files[0],
                async: false,
                cache: false,
                contentType: 'application/x-www-form-urlencoded',
                processData: false,
                success: function (returndata) {
                    alert(returndata);
                },
                error: function (returndata) {
                    alert(returndata);
                }
            });
        }
    </script>

界面元素以下:async

    <form id="uploadForm">
        <p>
            Pictures:
            <input type="file" name="picture" id="file1" />
        </p>
    </form>
    <input type="button" value="上傳" onclick="doUpload()" /> 

 另附Angular文件上傳代碼:函數

    <div ng-app="DemoApp" ng-controller="DemoController">
        <span class="input-group-addon">File Path:</span>
        <input type="file" id="file1" name="file1" neg-file-input ngf-select ng-model="file1" accept=".*" />
        <button type="button" ng-click="Upload()">Upload</button>
    </div>

JS部分:post

    var app = angular.module('DemoApp', []);

    app.controller('DemoController', ['$scope', '$http', function ($scope, $http) {
        //爲按鈕定義函數
        $scope.Upload = function () {
            var file = document.getElementById("file1").files[0];
            $scope.UploadHeader = {
                headers: { 'Content-Type': 'application/x-www-form-urlencoded' }
            }
            $http.post("up.ashx", file, $scope.UploadHeader)
                    .success(function (returndata) {
                        alert(returndata);
                    })
                    .error(function () {
                        alert(returndata);
                    });
        }

    }]);

Handle部分:url

        public void ProcessRequest(HttpContext context)
        {
            using (var inputStream = context.Request.InputStream)
            {
                string path = HttpContext.Current.Server.MapPath("UP");
                using (var flieStream = new FileStream(path + "/1.txt", FileMode.Create))
                {
                    inputStream.CopyTo(flieStream);
                }
            }
            context.Response.Write("ok");
        }
相關文章
相關標籤/搜索