• js文件上传


    工程:WebApi工程

    (1)文件流形式

     1 import React from 'react';
     2 import ReactDOM from 'react-dom';
     3 class Import extends React.Component {
     4     constructor(props) {
     5         super(props);
     6         this.bindHander();
     7     };
     8 
     9     bindHander() {
    10         this.openDisk = this.openDisk.bind(this);
    11         this.readFileContent = this.readFileContent.bind(this);
    12     };
    13 
    14     openDisk() {
    15         this.fileUpload.click();
    16     };
    17 
    18     readFileContent(e) {
    19         let
    20             _self = this,
    21             file = e.target.files[0];
    22         if (file) {
    23             let
    24                 reader = new FileReader();
    25             reader.readAsArrayBuffer(file);
    26             reader.onload = function () {
    27                 _self.props.uploadCallback(file.name, new Uint8Array(this.result));
    28             };
    29         } else
    30             console.log('error');
    31     };
    32 
    33     render() {
    34         return <input type="file" hidden ref={(el) => { this.fileUpload = el }} onChange={this.readFileContent} accept=".xml" />
    35     }
    36 };
    37 export default Import;
     1 import Import from './Import';
     2 const contants = {
     3     ERROR: 'Error',
     4     TIMEOUT: 'Load time out',
     5     LOADERROR: 'Load error!',
     6     URLCANNOTFIND: 'Url can not find'
     7 }
     8 
     9 export class Test extends React.Component {
    10     constructor(props) {
    11         super(props)
    12     };
    13 
    14     uploadClick() {
    15         this.import.openDisk()
    16     };
    17 
    18     uploadHandler(name, content) {
    19         g.loading(true);
    20         let
    21             uploadFile = {
    22                 name: name,
    23                 fileContent: content
    24             },
    25             request = {
    26                 method: 'POST',
    27                 headers: {
    28                     'Accept': 'application/json',
    29                     "Content-Type": "application/json"
    30                 },
    31                 credentials: "same-origin",
    32                 body: JSON.stringify(uploadFile)
    33             };
    34         fetch('api/test/fileupload', request).then(response => {
    35             if (response.ok)
    36                 return response.text();
    37             else {
    38                 if (response.status == 401) {
    39                     g.loading(false);
    40                     g.alert(true, {
    41                         title: contants.ERROR,
    42                         content: contants.TIMEOUT,
    43                         type: 'i',
    44                         clickY: () => { console.log(contants.LOADERROR) }
    45                     });
    46                 }
    47                 if (response.status == 400) {
    48                     g.loading(false);
    49                     g.alert(true, {
    50                         title: contants.ERROR,
    51                         content: contants.URLCANNOTFIND,
    52                         type: 'i',
    53                         clickY: () => { console.log(contants.LOADERROR) }
    54                     });
    55                 }
    56                 else throw new Error(response.statusText);
    57             };
    58         }).then(dataStr => {
    59             if (dataStr == null || dataStr == '')
    60                 return null;
    61             else return JSON.parse(dataStr);
    62         })
    63     }
    64 
    65     render() {
    66         return <div>
    67             <div onClick={this.uploadClick.bind(this)}>{'Upload Click'}</div>
    68             <Import
    69                 ref={el => this.import = el}
    70                 uploadCallback={this.uploadHandler.bind(this)}
    71             />
    72         </div>
    73     }
    74 }

     controller接受文件流

     1     [HttpPost, Route("fileupload")]
     2         public string FileUpload(UploadModel uploadModel)
     3         {
     4             byte[] buffer = new byte[uploadModel.fileContent.Count];
     5             for (int i = 0; i < uploadModel.fileContent.Count; i++)
     6             {
     7                 buffer[i] = (byte)(uploadModel.fileContent[i]);
     8             }
     9             return "success";
    10         }
    11 
    12         public class UploadModel
    13         {
    14             public string name { get; set; }
    15             public Dictionary<int, int> fileContent { get; set; }
    16         }

    (2)FormData

     1     uploadChange() {
     2         let
     3             self = this,
     4             element = $(ReactDOM.findDOMNode(this)),
     5             input = element.find('input[type="file"]')[0];
     6         let
     7             data = new FormData();
     8         data.append('file', input.files[0]);
     9         fetch('api/demo/uploadfile', {
    10             method: 'POST',
    11             headers: {
    12                 'Appect': 'application/json'
    13             },
    14             body: data
    15         }).then(r => {
    16             return r.json();
    17         }).then(json => {
    18             console.log(json);
    19         })
    20     }

    controller接收

            using System.Web;
    
            [HttpPost, Route("uploadfile")]
            public string UploadFile() {
                var file = HttpContext.Current.Request.Files[0];
                var aa = HttpContext.Current.Request.Form.Get("aa");
                return aa + "_" + file.FileName + "_" + file.ContentLength;
            }

    ==================================================================华丽的分割线=================================================================================

    工程:.NetCore

    fetch没整明白。接收的时候一直报错

    这里用ajax  和 FormData

     1  readFileContent(e) {
     2         let
     3             _self = this,
     4             file = e.target.files[0];
     5         if (file) {
     6             let
     7                 data = new FormData();
     8             data.append('file', file);
     9             console.log('import')
    10             $.ajax({
    11                 url: `${CommonUtil.getTargetUrlPrefix(SAComponents.COMPONENT_ASSESSMENTPRINTINGTRACKING)}/api/timeslots/importtimeslot`,
    12                 data: data,
    13                 method: 'POST',
    14                 processData: false,
    15                 contentType: false,
    16                 cache: false,
    17                 dataType: "json",
    18                 targetComponent: SAComponents.COMPONENT_ASSESSMENTPRINTINGTRACKING,
    19                 success: function (res) {
    20                     let
    21                         result = res;
    22                     console.log('success');
    23                 },
    24                 error: function (e) {
    25                     console.log(e);
    26                 },
    27                 headers: {
    28                     Authorization: "Bearer " + userProfileManager.getAccessToken()
    29                 },         
    30             });
    31         }
    32     };

    controller接收

    1         [HttpPost("importtimeslot")]
    2         public async Task<IActionResult> ImportTimeslot()
    3         {
    4             var file = HttpContext.Request.Form.Files[0];
    5             var command = new ImportTimeslotsCommand(file, TimeslotImportSheetName);
    6             var result = await _mediator.Send(command);
    7             return Request.OK(result);
    8         }

    表单提交

     1     importVenueChanged() {
     2         $$.loading(true);
     3         let urlPrefix = CommonUtil.getTargetUrlPrefix(SAComponents.COMPONENT_ADMINISTRATION), self = this,
     4             option = {
     5                 url: urlPrefix + '/api/venues/import',
     6                 targetComponent: SAComponents.COMPONENT_ADMINISTRATION,
     7                 method: 'POST',
     8                 success: function (res) {
     9                     console.log(this);
    10                 },
    11                 error: function (e) {
    12                     console.log(e);
    13                 }
    14             };
    15         $('#venueUploadForm').ajaxSubmit(option);
    16     }
    17 
    18     render() {
    19         return <form id="venueUploadForm" name="venueUploadForm" method="post" encType="multipart/form-data" style={{ display: "none" }}>
    20             <input id="importVenueFile" name="importVenueFile" type="file" onChange={this.importVenueChanged.bind(this)} />
    21         </form>
    22     }

    controller接收

    1 [HttpPost("import")]
    2 public async Task<IActionResult> Import()
    3 {
    4     var file = HttpContext.Request.Form.Files[0];
    5     var result = await _mediator.Send(new ImportVenueCommand(file.OpenReadStream()));
    6     return Request.Created("api/venues/viewreport", result);
    7 }
  • 相关阅读:
    angular模板
    Growth: 全栈增长工程师指南
    全栈增长工程师实战
    vue 快速搭建项目 iview
    ng-style
    教程视频链接
    内置对象
    对象—封装、继承
    对象—构造函数
    函数-理论
  • 原文地址:https://www.cnblogs.com/moran1992/p/9013075.html
Copyright © 2020-2023  润新知