Direct code
HTML page code:
< label > resource URL < / label > <input type="text" class="form-control" id="txtSourceURL" name="txtSourceURL"
Ng model = "editdata. Sourceurl" placeholder = "resource URL" ng MaxLength = "500" >
<! -- file address display -- >
< button id = "choosefile" onclick = "$('#fileupload'). Click()" > select file upload < / button >
Add this control to realize the function of selecting and uploading files, reduce the number of controls on the page, and facilitate the adjustment of styles -- >
<input id="fileUpload" type="file" onchange="$('#uploads').click()" style="display: none;" />
<! -- the browser's own upload file control. I also want to call the save() method directly for the change event, but it doesn't seem to work. I have to call through this transit. Let me know if you know -- >
< button ng Click = "save()" id = "uploads" style = "display: none;" > confirm upload < / button >
<! -- upload (save()) method must be called using other controls (buttons or tags) - >
controller.js code
app.controller('editController', ['$scope', "$http", 'webConfig', function ($scope, $http, webConfig) { $scope.save = function () { var fd = new FormData(); var file = document.querySelector('input[type=file]').files[0]; fd.append('logo', file); //angular The uploaded file must be processed in a special format, not json format $http({ method: 'POST', url: webConfig.apiRoot + "/api/ECategoryDetail/PostFiles", //"https://localhost:44320//api/ECategoryDetail/PostFiles" data: fd, headers: { 'Content-Type': undefined }, // Written as undifined,Browser is automatically converted to file upload type transformRequest: angular.identity }).success(function (response) { //Upload successful operation if (response.mark) //Whether the data flag bit returned by the interface is saved successfully. If it is saved successfully, the relative address of the file will be updated to the entity $scope.editdata.SourceURL = response.result; else alert("Upload failed"); }); }; }]);
webapi Code:
/// <summary> /// Upload file /// </summary> [HttpPost, Route("api/ECategoryDetail/PostFiles")] public IHttpActionResult PostFiles() { var result = ""; var filelist = HttpContext.Current.Request.Files; var mark = true; if (filelist.Count > 0) { for (var i = 0; i < filelist.Count; i++) { var file = filelist[i]; var fileName = file.FileName; var virtualPath = "/UploadFile/Files/"; var path = HttpContext.Current.Server.MapPath(virtualPath);//File full path if (!Directory.Exists(path)) { Directory.CreateDirectory(path); } var filePath = $"{path }{fileName}"; try { file.SaveAs(filePath); result = $@"{virtualPath}{fileName}"; } catch (Exception ex) { result = "Upload file write failed:" + ex.Message; mark = false; } } } else { result = "The uploaded file information does not exist!"; mark = false; } var json = new { result, mark }; return Ok(json); }
Welcome to communicate if you have any questions.