Home  >  Article  >  Web Front-end  >  Ajax cooperates with Spring to implement file upload function code

Ajax cooperates with Spring to implement file upload function code

韦小宝
韦小宝Original
2018-01-01 19:38:161097browse

Recently, I have been developing a web surface page that can upload images to the server. Here I will share with you the requirements and implementation ideas as well as the ajax source code. Friends who are interested in ajax can refer to the Ajax implementation with Spring File uploadfunction!

Due to project needs, develop a web form page that can upload images to the server.

1. Requirements

Web form page, you can upload pictures and other text information through the form.

2. The process of uploading pictures

I have never done this type of page before, so I can query the information. It is found that a common practice is to first upload the image to a file directory on the server side, and the server returns the storage path of the image to the front desk; then, the front desk submits the image storage path and other form information to the server, and all form information is stored in the database.

3. Method

Due to project needs, I will introduce two methods of image uploading here. The first one is to use ajax to directly upload an image. Upload; the second is to first cut the image into smaller files at the front desk, and then use ajax to upload the images to the server respectively, and the server will splice the files. (Method 2 is suitable for uploading larger files) Below I will introduce the two methods respectively.

Method 1: Directly upload the

1 html page


 

" /> 
 
 

 

 
这一部分需要注意的是,form表单的enctype属性必须设置为“multipart/form-data”,在Html5中,如果需要多张图片一起上传,可以在 标签中,增加multiple属性,例如:


2 js

(1)js使用ajax提供的ajaxfileupload.js库。这个库使用起来还是比较方便的,和普通的ajax函数使用方法几乎相同。首先,需要ajaxfileupload.js库文件。这里需要注意,我之前在网上下载了一个ajaxfileupload.js文件不能用,浪费了很长时间,我直接把js库文件粘贴到这里,方便分享。

// JavaScript Document
// ajax file uplaod 
jQuery.extend({ 
  createUploadIframe: function(id, uri) 
  { 
    //create frame 
    var frameId = 'jUploadFrame' + id; 
    if(window.ActiveXObject) { 
      var io = document.createElement('