⽂件上传去除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: '',
type: 'POST',
data: ElementById('file1').files[0],
async: false,
cache: false,
contentType: 'application/x-www-form-urlencoded',inputtypefile不上传文件
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 = dule('DemoApp', []);
//为按钮定义函数
$scope.Upload = function () {
var file = ElementById("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");
}
版权声明:本站内容均来自互联网,仅供演示用,请勿用于商业和其他非法用途。如果侵犯了您的权益请与我们联系QQ:729038198,我们将在24小时内删除。
发表评论