檔案上傳去除"Content-Disposition: form-data"

石曼迪發表於2016-04-07

某個專案中為了統一處理檔案上傳業務,建立了一個FileUpload Handle,由於上傳客戶端用到各種技術,當時為了方便斷點續傳,就直接接收請求中的檔案內容(可能是分片),所以處理的不是規範的http請求,一直工作的很好,但是現在使用html程式碼上傳檔案時遇到了問題:
服務接收到的檔案中會多一個頭和尾,原始內容如:

Part,Product
1,1
1,2

服務端接收到的如:

-----------------------------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來傳送請求:

    <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>

介面元素如下:

    <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部分:

    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部分:

        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");
        }

 

相關文章