jQuery插件之ajaxFileUpload上传文件或图片

版权声明:本文为博主原创文章,未经博主允许不得转载。 https://blog.csdn.net/yu_hongrun/article/details/82848479

我用的是这个:https://github.com/carlcarl/AjaxFileUpload

下载地址在这里:http://files.cnblogs.com/files/kissdodog/ajaxfileupload_JS_File.rar
AjaxFileUpload.js并不是一个很出名的插件,只是别人写好的放出来供大家用,原理都是创建隐藏的表单和iframe然后用JS去提交,获得返回值。

当初做了个异步上传的功能,选择它因为它的配置方式比较像jQuery的AJAX,我很喜欢。

ajaxFileUpload是一个异步上传文件的jQuery插件

语法:$.ajaxFileUpload([options])
 
options参数说明:

1、url           上传处理程序地址。

2、fileElementId      需要上传的文件域的ID,即的ID。

3、secureuri        是否启用安全提交,默认为false。

4、dataType        服务器返回的数据类型。可以为xml,script,json,html。如果不填写,jQuery会自动判断。

5、success        提交成功后自动执行的处理函数,参数data就是服务器返回的数据。

6、error          提交失败自动执行的处理函数。

7、data           自定义参数。这个东西比较有用,当有数据是与上传的图片相关的时候,这个东西就要用到了。

8、type           当要提交自定义参数时,这个参数要设置成post

使用方法:

第一步:先引入jQuery与ajaxFileUpload插件。注意先后顺序,这个不用说了,所有的插件都是这样。

  <script src="jquery-1.7.1.js" type="text/javascript"></script>
   <script src="ajaxfileupload.js" type="text/javascript"></script>

第二步:HTML代码:

 <div id="sys" class="col-md-4" style="margin-top: 25px;">
     <div class="tab-pane fade in active" id="systemConfig" >
         <form id="photoUploadForm">
             <div class="input-group">
                 <span class="input-group-addon">项目名称:</span>
                 <input type="text" name="name" id="name" value="${sysConfig.name}" class="form-control">
             </div>
             <div style="background: #6ccac9;margin-top: 20px;padding: 10px;">
                 <span style="margin: 15px;">当前项目Logo</span> <span  style="margin-left: 50px;">添加图片预览</span>
                 <div class="input-group" >
                     <image src="${sysConfig.images}" name="img" style="height: 80px;width: 80px; margin:20px;" alt="点击图片更换系统LOGO" />
                     <image id="chooseImg" onclick="replaceLogo()" src="/static/images/addImg.jpg"  value="" style="height: 80px;width: 80px;margin-left: 50px;" />
                     <input type="hidden"  id="photoUrl" name="images" value=""/>
                 </div>
             </div>
             <div class="input-group">
                 <p><input type="file" style="display: none;" onchange="inputChange(this)" id="uploadFile" name="uploadFile" accept="image/png,image/gif,image/jpg,image/jpeg" /></p>
                 <input type="button" class="btn btn-primary" value="保存" onclick="shangchuan()" style="margin-top: 25px;" />
             </div>
         </form>
     </div>
 </div>

第三步:JS代码

//当输入框的值发生改变时触发时间,预览图片必须用change事件,且change事件在HTML页面绑定,在js中绑定change事件第二次上传的时候不能预览,这是由于ajaxFileUpload插件克隆input组件导致的
function inputChange(e){
    $.ajaxFileUpload
    (
        {
            url: '/update/ajaxFileUpload', //用于文件上传的服务器端请求地
            method:"post",
            secureuri: false, //是否需要安全协议,一般设置为false
            fileElementId: 'uploadFile', //文件上传域的ID
            dataType: 'json',
            //返回值类型 一般设置为json
            success: function (d)  //服务器成功响应处理函数
            {
                if(d.state=="success"){
                    $("#chooseImg").attr("src",d.url);
                    $("#photoUrl").attr("value",d.url);
                }
            }
        }
    )
}

//点击添加图片打开上传文件的窗口
function replaceLogo() {
    $("#uploadFile").click();
}

第四步:后台FileUploadController代码:

package com.metro.crm.controller.base.controller;

import com.metro.crm.service.system.SettingService;
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.util.FileCopyUtils;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.multipart.MultipartFile;
import org.springframework.web.multipart.MultipartHttpServletRequest;

import javax.annotation.Resource;
import javax.imageio.ImageIO;
import javax.servlet.ServletContext;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.awt.*;
import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.HashMap;
import java.util.Map;

/**
 * 本地上传
 * [@author](https://my.oschina.net/arthor)
 *
 */
[@Controller](https://my.oschina.net/u/1774615)
@RequestMapping
public class FileUploadController{
    private static final Log logger = LogFactory.getLog(FileUploadController.class);

    /** 上传文件名 */
    private static final String UPLOAD_FILE_NAME = "uploadFile";

    /**
     * 前端获取服务器绝对路径图片
     * [@param](https://my.oschina.net/u/2303379) fileName
     * [@param](https://my.oschina.net/u/2303379) response
     */
    @RequestMapping(value = "/update/getImg", method = RequestMethod.GET)
    public void getImg(String fileName , HttpServletResponse response){
        File f = new File(fileName);
        try {
            String file = fileName.substring(fileName.lastIndexOf("/")+1,fileName.length());
            Image image = ImageIO.read(f);
            if(image == null){
                String fileExt = fileName.substring(fileName.lastIndexOf(".")+1,fileName.length()).toLowerCase();
                response.setContentType("application/octet-stream;");
                response.setHeader("Content-Disposition", "attachment;fileName="+file);
            }
            FileCopyUtils.copy(new FileInputStream(f), response.getOutputStream());
        } catch (IOException e) {
            // TODO 自动生成的 catch 块
            e.printStackTrace();
        }
    }

    @ResponseBody
    @RequestMapping(value = "/update/ajaxFileUpload", method = RequestMethod.POST)
    public Map<String,Object> ajaxFileUpload(HttpServletRequest request, HttpServletResponse response){
        MultipartHttpServletRequest multipartRequest  =  (MultipartHttpServletRequest) request;
        MultipartFile uploadFile = multipartRequest.getFile(UPLOAD_FILE_NAME);
        Map<String, Object> map = new HashMap<String, Object>();
        if (uploadFile == null) {
            map.put("status", "error");
            map.put("message", "上传失败:文件为空");
            return map;
        }
        try {
            //1.文件存储在临时目录上
            String fileName = uploadFile.getOriginalFilename();
            //获取上传文件类型的扩展名,先得到.的位置,再截取从.的下一个位置到文件的最后,最后得到扩展名
            String fileExt = fileName.substring(fileName.lastIndexOf("."),fileName.length()).toLowerCase();
            SimpleDateFormat sdf = new SimpleDateFormat("yyyyMMddHHmmss");
            String newName = sdf.format(new Date());
            //获取当前项目根目录
            String path = request.getSession().getServletContext().getRealPath("");
            File filePath=new File(path);
            path = filePath.getParentFile().getParent()+"/upload";
            //获取文件夹位置(用作判断文件夹是否存在)
            File file =new File(path);
            //如果文件存在,则删除文件夹下面的文件,保证文件夹中只有当前上传的一张图片,上传多张的则不需要这个判断
            if(file .exists()){
                File[] files = file.listFiles();
                for (int i = 0; i < files.length; i++) {
                    if (files[i].isFile()){
                        File photoFile = new File(files[i].getPath());
                        photoFile.delete();
                    }
                }
            }
            //如果文件夹不存在则创建
            if  (!file .exists()  && !file .isDirectory()){
                //创建upload目录
                file.mkdir();
            }
            //把图片放在项目根目录的上一级目录(防止系统更新导致文件丢失)
            path+= "/"+newName+fileExt;
            //前端获取绝对路径图片
            path=path.replace("\\","/");
            String frontImg = "/update/getImg?fileName="+path;
            File f = new File(path);
            //保存到指定目录
            uploadFile.transferTo(f);
            map.put("state", "success");
            map.put("message","上传成功" );
            //返回给kindEditor
            map.put("url",frontImg );
            return map;
        } catch (IOException e) {
            String msg   = "上传文件失败:"+e.getMessage();
            logger.info("=========="+msg);
            map.put("state", "error");
            map.put("message",msg );
            return map;
        }
    }
}

项目运行效果图:
在这里插入图片描述

猜你喜欢

转载自blog.csdn.net/yu_hongrun/article/details/82848479