.Net Core WebApi two ways to upload pictures

I am here mainly to upload pictures, I did not talk much on the code.

Method 1: Upload via Form Form

rear end:

Copy the code
     /// <the Summary> 
        /// upload pictures, submitted by Form Form 
        /// </ the Summary> 
        /// <returns A> </ returns A> 
        [Route ( "the Upload / FormImg")] 
        [HttpPost] 
        public ActionResult UploadImg ( List <IFormFile> files) 
        { 
            IF (files.Count <. 1) 
            { 
                return Error ( "file is empty"); 
            } 
            // return the address of the file 
            List <String> List of the filenames new new = <String> ();             
            var now = the DateTime.Now; 
            // file storage path 
            var filePath = string.Format ( "/ Uploads / {0} / {1} / {2} /", now.ToString ( "yyyy"), now.ToString ( "yyyyMM"), now.ToString("yyyyMMdd"));
            // get the current web directory 
            var webRootPath = _hostingEnvironment.WebRootPath;
            IF (Directory.Exists (webRootPath + filePath)!) 
            { 
                Directory.CreateDirectory (webRootPath + filePath); 
            } 
            the try 
            { 
                the foreach (Files in Item var) 
                { 
                    IF (! Item = null) 
                    { 
                        #region image file condition judgment 
                        // file suffix 
                        var fileExtension = Path.GetExtension (item.FileName); 

                        // determine whether the suffix is the picture 
                        const String fileFilt = ".gif | .jpg | .jpeg | .png"; 
                        iF (fileExtension == null) 
                        { 
                            BREAK; 
                            // return Error ( "upload file no suffix"); 
                        } 
                        IF (fileFilt.IndexOf (fileExtension.ToLower (), StringComparison.Ordinal) <= -1) 
                        { 
                            BREAK; 
                            / / return Error ( "Please upload images jpg, png, gif format"); 
                        } 

                        // determine the file size     
                        Long length = item.Length; 
                        IF (length> 1024 * 1024 * 2) // 2M 
                        { 
                            BREAK;
                            // return Error ( "upload file can not be greater than 2M"); 
                        }

                        #endregion 

                        var strDateTime = DateTime.Now.ToString ( "yyMMddhhmmssfff"); // string acquisition time 
                        . var strRan = Convert.ToString (new Random () Next (100, 999)); // generates three random numbers 
                        var SAVENAME strRan + + = strDateTime fileExtension; 

                        // insert picture data                  
                        the using (FS = System.IO.File.Create the FileStream (filePath webRootPath + + SAVENAME)) 
                        { 
                            Item .CopyTo (FS); 
                            fs.Flush (); 
                        } 
                        filenames.Add (filePath SAVENAME +); 
                    } 
                } 
                return Success (of the filenames) ; 
            } 
            the catch (Exception EX)
            { 
                // here increasing log records cause of the error 
                //ex.ToString (); 
                return Error ( "Upload failed"); 
            } 
        }
Copy the code

I am here mainly to render the image data, so there is more to the picture file to determine the conditions, where according to the needs, self-adjusting. Including storage files.

 

front end:

Copy the code
<!DOCTYPE html>
<html>
<head>
    <title>.Net Core WebApi图片上传</title>
    <meta charset="utf-8"/>
    <script type="text/javascript" src="/js/jquery-1.10.2.min.js"></script>
    <script type="text/javascript" src="/js/jquery.form.min.js"></script>
</head>
<body>
<h1>通过form表单提交</h1>
<form id="myform" name="myform" method="post" enctype="multipart/form-data" 
                    action="https://localhost:44376/Upload/FormImg">
    <input type="file" name="files" id="files" value="Select files to upload "Multiple /> 
   upload pictures, return address
<div>
</ form>
    <the INPUT of the type =" the Button "the above mentioned id =" submitbtn "value =" submit "onclick =" uplpadfile ( ">)

< / div> <div the above mentioned id =" imglist "> </div> <script type="text/javascript">

    //前端第一种提交方式 function uplpadfile(){ //获取表单的数据 var formdata var file = $("#files").get(0); var files = file.files; var formdata = new FormData(); for (var i = 0; i < files.length; i++) { formdata.append("files", files[i]); } $.ajax({ type:'Post', data:formdata, contentType: false, processData: false, url:"https://localhost:44376/Upload/FormImg", Success: function (Result) { if (result.Success) { result.Data imglist = var; for (var I in imglist) { $ ( "# imglist") the append ( '<IMG the src = "' + imglist [I] + '" />');. } } the else { Alert ( 'commit fails, retry submission'); } } }) }; </ Script> </ body> </ HTML>
Copy the code

In addition to uploading submit written the way, there are two other submission of data:

Second way:

Copy the code
function  uplpadfile(){
        //获取表单的数据        
        var formdata = new FormData(document.getElementById("myform"));

        $.ajax({
            type:'Post',
            data:formdata,                        
            contentType: false,
            processData: false,
            url:"https://localhost:44376/Upload/FormImg",
            success:function(result){
                if (result.Success) {
                    var imglist =result.Data; 
                    for(var i in imglist){
                        $("#imglist").append('<img src="'+imglist[i]+'"/>');
                    }                    
                the else {}                     
                    Alert ( 'commit fails, retry submission'); 
                }                             
            } 
        }) 
    }; 
</ Script>
Copy the code

 

 Three ways:

Copy the code
<script type="text/javascript">
    function  uplpadfile(){

        $("#myform").ajaxSubmit(function(result){
            if (result.Success) {
                var imglist =result.Data; 
                for(var i in imglist){
                    $("#imglist").append('<img src="'+imglist[i]+'"/>');
                }                    
            }else{                    
                alert('提交失败,重新尝试提交');
            }
        });
        
    };
</script>
Copy the code

  

The front here, points to note:

 1, Form table must be coupled with   enctype = "multipart / form-data "   tab

 2, the file upload control file, if you want to upload multiple images, you need to add  multiple  labels

 3, in a manner:  formdata.append ( "files", files [I])    of the   files   must accept the same parameters and the interface file name

 4 Form Two and Three ways: <the INPUT of the type = "File" name = "Files">   The  name  must accept the same parameters and interfaces file name

 

Form submission by way of summary:

The front end of the submission of documents can be used in three ways.

If the file to be submitted along with the form and other data, you can use the second and third approach.

If you only want to submit a separate data file, you can use a.

 

==================== gorgeous dividing line ====================

 

Second way: by uploading Base64 character

rear end:

Copy the code
     /// <summary>
        /// 文件上传,Base64
        /// </summary>
        /// <param name="fileBase64">Base64</param>
        /// <param name="fileName">文件名</param>
        /// <returns></returns>
        [HttpPost]
        [Route("Upload/Base64")]
        public ActionResult UploadBase64(string fileBase64, string fileName)
        {
            byte[] bytes = fileBase64.ToBytes_FromBase64Str();
            var fileExtension = Path.GetExtension(fileName);
            var strDateTime = DateTime.Now.ToString("yyMMddhhmmssfff"); //取得时间字符串
            var strRan = Convert.ToString(new Random().Next(100, 999));// generate three random numbers
            var saveName = strDateTime + strRan + fileExtension;
            var savePath = "Upload/Img/" + DateTime.Now.ToString("yyyyMMdd") + "/" + saveName;
            string filePath = "https://oss.tiaobox.com/" + savePath;
            try
            {
                //将文件上传到阿里云oss
                using (MemoryStream m = new MemoryStream(bytes))
                {
                    var client = new OssClient(aliyunconfig.EndPoint, aliyunconfig.AccessKeyID, aliyunconfig.AccessKeySecret);
                    PutObjectRequest _objRequest = new PutObjectRequest(aliyunconfig.BucketName, savePath, m);
                    client.PutObject(_objRequest);
                }
                Success return (filePath); 
            }
            the catch (Exception EX) 
            { 
                WriteSysLog (ex.ToString (), the interface call Entity.Base_SysManage.EnumType.LogType exception.); 
                return Error ( "Upload failed!");                 
            } 
            
        }
Copy the code

 

This backend method, you can only upload a file, the front need to convert the file to Base64 character of submission.

Way to save data here is saved to Ali cloud OSS, the above method can also be used, stored locally. Ultimately returns the file path.

 

front end:

Copy the code
<! DOCTYPE HTML> 
<HTML> 
<head> 
    <title> .Net Core WebApi upload pictures </ title> 
    <Meta charset = "UTF-8" /> 
    <Script of the type = "text / JavaScript" src = "/ JS / 1.10.2.min.js-jQuery "> </ Script> 
    <Script type =" text / JavaScript "the src =" / JS / jquery.form.min.js "> </ Script> 
</ head> 
<body> 
<h1> submit </ h1> through documents into Base64 character 

<input type = "file" name = "basefile" id = "basefile" value = " select files to upload" Multiple /> 


<Script of the type = "text / JavaScript "> 
    $ (" # basefile "). Change (function () { 
        var basefile = Base64 (document.getElementById ("basefile ")); 
    }) 

    // upload 
    function updateBackground (filename, imgurl) {
 
      // Before submission, removing formatting tags
      imgurl =  imgurl.replace("data:image/jpeg;base64,", "").replace("data:image/png;base64,", "").replace("data:image/jpg;base64,", "").replace("data:image/gif;base64,", "").replace("data:image/bmp;base64,", "");
      // urlElement.innerHTML = imgurl;
      var businessParam = {
            fileBase64:imgurl,
            fileName:filename
        };

      $.ajax({
        url:'https://localhost:44376/Upload/Base64',
        data:businessParam,
        type:'post',
        dataType:'json',
        success:function(result){
            if (result.Success) { 
            } the else {                    
                Alert ( "successful upload");
                Alert ( "upload failed");
            }                 
        }, 
        Error: function (Data) {                 
            Alert ( "error:" + data.Error); 
        } 
      }) 

    } 


    // documents into the Base64 
    function Base64 (File) { 
        IF (typeof (the FileReader) === 'undefined' ) { 
           Alert ( "Sorry, your browser does not support the FileReader, use modern browsers operation!"); 
        } 
        var Reader the FileReader new new = ();             
        var = file.files POS [0] .name.lastIndexOf (. " "); 
        var = file.files type [0] .name.substring (+ POS. 1);             
        // determine the file format
        if (type.toLowerCase() != "png" && type.toLowerCase() != 'jpg' && type.toLowerCase() != 'jpeg' && type.toLowerCase() != 'gif' && type.toLowerCase() != 'bmp') {
            alert("格式错误,请上传'png、jpg、jpeg、bmp、gif'格式文件");
            return;
        }
        
        reader.onloadend = (
            function(e) {
                imgurl = e.target.result;
                updateBackground(file.files[0].name,imgurl);
            }
        );        
        // Read the file
        reader.readAsDataURL(file.files[0]);
        
    }
</script>
</body>
</html>
Copy the code

 

It should be noted that turn into Base64 character files, need to remove the label format file at the tip in front of the character. Otherwise Base64-to-back characters will not be read properly.

In the rear end or receiving data, processing can be done.

 

supplement:

The definition of _hostingEnvironment

Copy the code
private readonly IHostingEnvironment _hostingEnvironment;
        public UploadController(IHostingEnvironment hostingEnvironment,IOptions<AliyunConfig> _aliyunconfig)
        {
            _hostingEnvironment = hostingEnvironment;
            aliyunconfig = _aliyunconfig.Value;
        }
Copy the code

 

ToBytes_FromBase64Str String class method is an extension

  public static byte[] ToBytes_FromBase64Str(this string base64Str)
  {
        return Convert.FromBase64String(base64Str);
  }

 

 If any error or lack of place, please correct me, learn from each other.

 

 

Reference article, there is also talk about uploading large files:

https://www.cnblogs.com/seabluescn/p/9229760.html

 

Turn: https: //www.cnblogs.com/leoxuan/articles/11087121.html

Guess you like

Origin www.cnblogs.com/pingming/p/11330921.html