Picture upload ajax asynchronous submission and synchronous submission and preview the picture upload to the Web site directory file detailed explanation FormData () object

Preface

Today I will share with you about "Pictures uploaded and previewed and saved in the directory folder of the website"   

a) Synchronous submission (page-level submission)

Front-end code

(1) Through the form; input type="file" tag type is file

 <form id="form1" runat="server">
        <div>
            <input type="file"  name="file" />
            <input type="submit" value="上传" />
        </div>
    </form>

(2) Submit the entire form on the page to the server and refresh the page;
(3) If a file is included, the file will be packaged as a byte stream and uploaded to the server;
(4) Use the Request object in the backend to get the form Element input tag; Request["file"]; The key value here is the name value of the input tag . Be careful here! (5) this time to get the picture file path is an absolute path

Backend code

            string filePath = Request["file"];
            if (filePath == null) return;
            string filename = filePath.Substring(filePath.LastIndexOf("\\") + 1);
            string fileEx = filePath.Substring(filePath.LastIndexOf(".") + 1);
            string paths = filename.Substring(0, filename.IndexOf("."));    
            //合成站点下的站点下的images目录文件
            string serverpath = Server.MapPath(@"~\images\") + filename;
            //实例化并获取客户端上传的文件对象
            System.Drawing.Image image = System.Drawing.Image.FromFile(filePath);
            //保存图片至站点下的images目录文件
            image.Save(serverpath);
            image.Dispose();

(6) Use string interception method. Get the name of the file (including the suffix) ====> string filename = filePath.Substring(filePath.LastIndexOf("\") + 1);
(7) Use string interception method. Get the file extension ====> string fileEx = filePath.Substring(filePath.LastIndexOf(".") + 1);
(8) Use string interception method. Get the name of the file (not including the suffix) ====> string paths = filename.Substring(0, filename.IndexOf("."));

b) Asynchronous upload (submitted via ajax)

(1) Generally, when accessing webapi, upload data using JSON format data transmission method;
(2) In special circumstances, if you want to upload files, use the FormData object to simulate form submission;
(3) JS The FormData object will submit the data like synchronously submitting the form, and then the file can be included in the FormData and submitted together;

front end

js code

                                        var form = new FormData();
                                         form.append("file", $('#file')[0].files[0]);
                                         $.ajax({
    
    
                                             url: "/pages/WebAPI",
                                             method: "post",
                                             contentType: false,
                                             processData: false,
                                             dataType: false,
                                             data: form,
                                             success: function (result) {
    
    
                                             //上传成功回调函数                                    
                                             }
                                         });

(4) The use of FormData
var form = new FormData();
append data to formdata; parameters are in the form of data name and data value;
form.append('name', value);
add files to formdata; parameter is name And file object; the name here has no practical effect; but it must be in the form of file
form.append('file', fileObj);
(5) You can see this statement
form.append("file", $('# file')[0].files[0]); In
$('#file')[0].files[0], why add [0] to $('#file')?
This statement means to get the file object whose id is the file tag, and adding [0] is to convert JQ syntax into Javascript syntax.
1) In JQuery-var fileObj = $('#file')[0]. files[0];
2) In JavaScript-varfileObj=document.getElementById('file').files[0];
So the .files[0] attribute is in javascript, so JQ needs to be converted to JS.

>使用异步上传的注意点

(6) When using the FormData object to upload data, the get method is not allowed.
(7) When using the FormData object to upload data containing files, directly using $.post() is invalid.
(8) When using the FormData object to upload data containing files , You must use the $.ajax() method
(9) The submission method must be post.

         $.ajax({
    
    
				url: '',
				method: 'post', //由于jq的版本问题,这个参数在有的地方也叫做type
				dataType: 'json',
				contentType: false, //必须是false
				processData: false, //必须是false
				success: function(){
    
    }
			})
Picture Preview

If you want a picture preview, it’s much easier

                                         var file = $('#file')[0].files[0];
                                         if (file) {
    
    
                                             var reader = new FileReader();
                                             reader.readAsDataURL(file);
                                             reader.onloadend = function (even) {
    
    
                                                 $('#file_img').attr("src", even.currentTarget.result);
                                             }
                                         }
Backend code
  private string SaveImage()
        {
    
    
           string result = "";
            if (!Directory.Exists(Server.MapPath("/images/Userimg")))
            {
    
    
                Directory.CreateDirectory(Server.MapPath("/images/Userimg"));
            }
            HttpPostedFile file = Request.Files[0];
            if (!file.ContentType.Contains("image/"))
            {
    
    
                result = Newtonsoft.Json.JsonConvert.SerializeObject(new
                {
    
    
                    Code = 10002,
                    Message = "传输文件格式不正确!"
                });
                
            }else{
    
    
            Random ran = new Random();
            String fileName ="img"+ran.Next(1000,9999).ToString();
            String filesuffix = this.GetFileSuffix(file.ContentType);
            String fullName = Path.Combine("/images/Userimg/", fileName + filesuffix);
            file.SaveAs(Server.MapPath(fullName));
              result = Newtonsoft.Json.JsonConvert.SerializeObject(new
               {
    
    
                    Code = 10002,
                    Message = "传输文件格式不正确!"
              });
           }
          return result;
        }

        /// <summary>
        /// 获取图片文件的  扩展名
        /// </summary>
        /// <param name="mimeType"></param>
        /// <returns></returns>
        private string GetFileSuffix(string mimeType)
        {
    
    
            string suffix = string.Empty;
            switch (mimeType)
            {
    
    
                case "image/png":
                    suffix = ".png";
                    break;
                case "image/jpeg":
                    suffix = ".jpg";
                    break;
                case "image/gif":
                    suffix = ".gif";
                    break;
                default:
                    suffix = ".jpg";
                    break;
            }

            return suffix;
        }

(1) Determine whether the path of the file to be uploaded exists, and if it does not exist, create it.
(2) Obtain the file collection uploaded by the client in the multi-part MIME format, that is, HttpPostedFile file = Request.Files[0];
(3) Interpret the type of the current file object
(4) Realize that the same file can be uploaded multiple times, To avoid unnecessary errors, give him a random four-digit number and rename it
(5) HttpPostedFile can provide a direct save object [SaveAs()], just provide the parameters of the save file address.

Application effect


That small project usually saves the file in the site directory file. Why on earth?
a) Ensure the correctness of the access directory
b) Ensure the accessibility of the file (the most important reason)
c) When the project is released, the user accessing the file is IIS_USER, if it is in other directories, there is no access authority;

At last

Well, today’s study and finishing is over. Welcome to point out deficiencies and sincerely accept criticism.

Guess you like

Origin blog.csdn.net/WenRouDG/article/details/107993317