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

某个项目中为了统一处理文件上传业务,创建了一个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");
        }

 

posted @ 2016-04-07 10:59  石曼迪  Views(17790)  Comments(1Edit  收藏  举报
瓴域建设-环保事业中心