以下代码已生成,并已连接到.net核心中称为“流”的控制器。该代码运行良好,可以完美地附加大文件。
该代码需要在另一个html页面中使用,以用于不同目的的文件上传。但是,当按下上传按钮时,将显示以下错误:
无法加载资源:服务器的响应状态为400(错误请求)
在这种情况下,如果我从原始页面附加文件,则该过程完成,然后可以从复制的页面附加任何文件!
但是,如果我关闭浏览器并尝试从复制的页面附加文件,则会显示错误。
<div class="panel-body" ng-app="myApp">
@*Attachment*@
<div ng-app="myApp">
<div ng-controller="myCtrl">
<div>
@if (ViewBag.Attachments != null)
{
foreach (var a in ViewBag.Attachments)
{
var id = @a.AttachmentId;
@lastattachid = id;
<div class="row">
<div class="col-xs-12 left">
<a asp-action="Download" asp-route-path="@a.FilePath\\@a.FileName">@a.FileName</a>
<div style=" position: absolute;top: 2px;right: 2px;">
@if (ViewBag.recepient.Equals(@a.CreatedBy))
{
var FilePath = @a.FilePath.Replace("\\", "\\\\");
<a onclick='deleteattachment(@a.AttachmentId, "@a.FileName", "@FilePath")'>✘</a>
}
</div>
</div>
</div>
}
}
</div>
<hr />
<div>
<div>
<div>
<input name="attachedfile" type="file" file-model="attachedfile" />
</div>
</div>
<br />
<div>
<button ng-click="uploadAttachment()">Upload</button>
</div>
</div>
</div>
</div>
</div>
<script src="http://ajax.googleapis.com/ajax/libs/angularjs/1.3.14/angular.min.js">
</script>
<script>
var Attachment = (function () {
function Attachment(customer, invoice, name, dwg, attachedfile) {
this.attachmentid = @lastattachid + 1;
this.customer = customer;
this.jobInv = invoice;
this.jobName = name;
this.jobDwg = dwg;
this.path = "\\@ViewBag.customerId\\" + invoice + ";" + name + ";" + dwg + "\\";
this.fileName = attachedfile.name;
this.attachedfile = attachedfile;
}
return Attachment;
}());
var myApp = angular.module('myApp', []);
myApp.directive('fileModel', ['$parse', function ($parse) {
return {
restrict: 'A',
link: function (scope, element, attrs) {
var model = $parse(attrs.fileModel);
var modelSetter = model.assign;
element.bind('change', function () {
scope.$apply(function () {
modelSetter(scope, element[0].files[0]);
});
});
}
};
}]);
myApp.service('attachmentService', ['$http', function ($http) {
this.uploadAttachment = function (attachment) {
var fd = new FormData();
fd.append('AttachmentId', attachment.attachmentid);
fd.append('Customer', attachment.customer);
fd.append('JobInv', attachment.jobInv);
fd.append('JobName', attachment.jobName);
fd.append('JobDwg', attachment.jobDwg);
fd.append('Name', attachment.fileName);
fd.append('Path', attachment.path);
fd.append('attachedfile', attachment.attachedfile);
return $http.post('/Streaming/Upload', fd, {
transformRequest: angular.identity,
headers: {
'Content-Type': undefined
}
});
};
}]);
myApp.controller('myCtrl', ['$scope', 'attachmentService', function ($scope, attachmentService) {
$scope.uploadAttachment = function () {
$scope.showUploadStatus = false;
$scope.showUploadedData = false;
var attachment = new Attachment("@customerid","@inv", " ", " ", $scope.attachedfile);
attachmentService.uploadAttachment(attachment).then(function (response) { // success
if (response.status === 200) {
var inv = "@inv";
inv = inv.replace("&", "%26");
var job = "@job";
job = job.replace("&", "%26");
var dwg = "@dwg";
dwg = dwg.replace("&", "%26");
window.location.href = "/Quote/Details/@ViewBag.customerId?quoteno=" + inv;
}
},
function (response) { // failure
$scope.uploadStatus = "Attachment upload failed with status code: " + response.status;
$scope.showUploadStatus = true;
$scope.showUploadedData = false;
$scope.errors = [];
$scope.errors = parseErrors(response);
});
};
}]);
function parseErrors(response) {
var errors = [];
for (var key in response.data) {
for (var i = 0; i < response.data[key].length; i++) {
errors.push(key + ': ' + response.data[key][i]);
}
}
return errors;
}
</script>
已更新:
服务器端代码如下:
[HttpPost]
[DisableFormValueModelBinding]
[ValidateAntiForgeryToken]
public async Task<IActionResult> Upload()
{
if (string.IsNullOrEmpty(userManager.GetUserName(User)))
return RedirectToAction(actionName: "Login", controllerName: "Account");
if (!MultipartRequestHelper.IsMultipartContentType(Request.ContentType))
{
return BadRequest($"Expected a multipart request, but got {Request.ContentType}");
}
// Used to accumulate all the form url encoded key value pairs in the
// request.
var formAccumulator = new KeyValueAccumulator();
string targetFilePath = Directory.GetCurrentDirectory() + "\\wwwroot\\Attachment";
string fileName = "";
var boundary = MultipartRequestHelper.GetBoundary(
MediaTypeHeaderValue.Parse(Request.ContentType),
_defaultFormOptions.MultipartBoundaryLengthLimit);
var reader = new MultipartReader(boundary, HttpContext.Request.Body);
var section = await reader.ReadNextSectionAsync();
while (section != null)
{
ContentDispositionHeaderValue contentDisposition;
var hasContentDispositionHeader = ContentDispositionHeaderValue.TryParse(section.ContentDisposition, out contentDisposition);
if (hasContentDispositionHeader)
{
if (MultipartRequestHelper.HasFileContentDisposition(contentDisposition))
{
using (var targetStream = System.IO.File.Create(targetFilePath + fileName))
{
await section.Body.CopyToAsync(targetStream);
_logger.LogInformation($"Copied the uploaded file '{targetFilePath + fileName}'");
}
}
else if (MultipartRequestHelper.HasFormDataContentDisposition(contentDisposition))
{
// Content-Disposition: form-data; name="key"
//
// value
// Do not limit the key name length here because the
// multipart headers length limit is already in effect.
var key = HeaderUtilities.RemoveQuotes(contentDisposition.Name);
var encoding = GetEncoding(section);
using (var streamReader = new StreamReader(
section.Body,
encoding,
detectEncodingFromByteOrderMarks: true,
bufferSize: 1024,
leaveOpen: true))
{
// The value length limit is enforced by MultipartBodyLengthLimit
var value = await streamReader.ReadToEndAsync();
value = value.Replace("&", "&");
if (String.Equals(value, "undefined", StringComparison.OrdinalIgnoreCase))
{
value = String.Empty;
}
formAccumulator.Append(key, value);
if (key.Equals("Path"))
{
targetFilePath += value;
Directory.CreateDirectory(targetFilePath);
}
if (key.Equals("Name"))
fileName = value;
if (formAccumulator.ValueCount > _defaultFormOptions.ValueCountLimit)
{
throw new InvalidDataException($"Form key count limit {_defaultFormOptions.ValueCountLimit} exceeded.");
}
}
}
}
// Drains any remaining section body that has not been consumed and
// reads the headers for the next section.
section = await reader.ReadNextSectionAsync();
}
// Bind form data to a model
var attachment = new AttachFile();
var formValueProvider = new FormValueProvider(
BindingSource.Form,
new FormCollection(formAccumulator.GetResults()),
CultureInfo.CurrentCulture);
var bindingSuccessful = await TryUpdateModelAsync(attachment, prefix: "",
valueProvider: formValueProvider);
if (!bindingSuccessful)
{
if (!ModelState.IsValid)
{
return BadRequest(ModelState);
}
}
var user = userManager.GetUserName(User);
// Add attachmnet to a jason file
// ...
var uploadedData = new UploadedData()
{
Invoice = attachment.JobInv,
Name = attachment.JobName,
Dwg = attachment.JobDwg,
FileName = attachment.FileName,
FilePath = targetFilePath,
CreatedBy = user,
CreatedDate = DateTime.Now
};
return Json(uploadedData);
}
public class AttachFile
{
public int AttachmentId { get; set; }
public string Customer { get; set; }
public string JobInv { get; set; }
public string JobName { get; set; }
public string JobDwg { get; set; }
public string FileName { get; set; }
public string FilePath { get; set; }
public string CreatedBy { get; set; }
public DateTime CreatedDate { get; set; }
}
public class UploadedData
{
public string Invoice { get; set; }
public string Name { get; set; }
public string Dwg { get; set; }
public string FileName { get; set; }
public string FilePath { get; set; }
public string Path { get; set; }
public string CreatedBy { get; set; }
public DateTime CreatedDate { get; set; }
}