浏览器图片\文件上传到服务器 ajaxfileupload.js使用实例

在电商项目中经常遇到图片或者文件上传的需求,但是现在的浏览器为了安全起见都封闭了file控件上传的本地绝对路径,所以我用一个js插件完成上传需求

现在我把我写的代码拿出关键部分当个例子分享给大家,希望大家多多指教

第一步 在页面引入ajaxfileupload.js插件

第二步 在页面js中写代码:

//保存提交事件
 function saveData(status) {
 	if(!$("#myform").valid()){
 		return;
 	}
 	var id = $("#id").val();
 	var goodsCategory1Id = $("#goodsCategory1Id").val();
 	var brandId1 = $("#brandId1").val();
 	var brandId2 = $("#brandId2").val();
 	var brandId3 = $("#brandId3").val();
 	var brandId4 = $("#brandId4").val();
 	var brandId5 = $("#brandId5").val();
 	var brandId6 = $("#brandId6").val();
 	var order1 = $("#order1").val();
 	var order2 = $("#order2").val();
 	var order3 = $("#order3").val();
 	var order4 = $("#order4").val();
 	var order5 = $("#order5").val();
 	var order6 = $("#order6").val();
 	var hotAdv = $("#fileName").val();
 	 $.ajaxFileUpload( {  
         url : "/salesAdvertisement/save.ajax",//用于文件上传的服务器端请求地址  
         secureuri : false,//一般设置为false  
         fileElementId : 'fileName',//文件上传控件的id属性  
         dataType : 'json',//返回值类型 一般设置为json  
         data: {
        	 "goodsCategoryGrade1Id" : goodsCategory1Id,
  			"brandId1" : brandId1,"brandId2" : brandId2,"brandId3" : brandId3,"brandId4" : brandId4,"brandId5" : brandId5,"brandId6" : brandId6,
  			"brandOrder1" : order1,"brandOrder2" : order2,"brandOrder3" : order3,"brandOrder4" : order4,"brandOrder5" : order5,"brandOrder6" : order6,
  			"img" : hotAdv,"id":id,"status":status
         },  
         success : function(data, status){ //服务器成功响应处理函数  
             alert(data.message);//从服务器返回的json中取出message中的数据,其中message为在struts2中定义的成员变量  
             if (typeof (data.error) != 'undefined') {  
                 if (data.error != '') {  
                     alert(data.error);  
                 } else {  
                     alert(data.message);  
                 }  
             }  
         },  
         error : function(data, status, e){//服务器响应失败处理函数  
             alert(e);  
         }  
     }) ;
 	
 }
第三步后端controller接收代码:

/**
     * 保存导航热卖广告
     * @param webUserForm
     * @return
     */
    @ResponseBody
    @RequestMapping(value = "/save.ajax")
    public String save(SpdBestSellerAdvertisementForm spdBestSellerAdvertisementForm, HttpServletRequest request) {
        logger.runTrail("保存导航热卖广告", "save", spdBestSellerAdvertisementForm);
        WebResult m = new WebResult();
        try {
            MultipartHttpServletRequest multipartRequest = (MultipartHttpServletRequest) request;
            /**页面控件的文件流**/
            MultipartFile multipartFile = multipartRequest.getFile("fileName");

            //执行新建或者更新操作
            ResultDto result = adminSpdSellerAdvertisementModel.save(spdBestSellerAdvertisementForm,
                multipartFile);
            m.setResult(result);
            m.setSuccess(result.getSuccess());
            m.setMessage(result.getMessage());
        } catch (Exception ex) {
            m.setSuccess(false);
            m.setMessage("system_error");
            logger.exception("/save.ajax", "保存仓库信息异常", ex);
        }
        return JsonUtilsHelper.toJson(m);
    }

第四步 后端modle处理代码

/**
           * 保存广告信息
           * @param channelStorageEntity
           * @return
           */
    public ResultDto save(SpdBestSellerAdvertisementForm spdBestSellerAdvertisementForm,
                                   MultipartFile multipartFile) {
        String imgUrl = null;
        if (null != spdBestSellerAdvertisementForm.getImg() && !"".equals(spdBestSellerAdvertisementForm.getImg())) {
            //图片保存到本地服务器
            //imgUrl = saveImageLocal(spdBestSellerAdvertisementForm.getImg());
            //保存到远程服务器
            imgUrl = saveImageRomate(multipartFile);
        }

        spdBestSellerAdvertisementForm.setImg(imgUrl);
        Date date = new Date();//如果不需要格式,可直接用dt,dt就是当前系统时间
        spdBestSellerAdvertisementForm.setModifyTime(date);
        spdBestSellerAdvertisementForm.setCreateTime(date);
        spdBestSellerAdvertisementForm.setCreateUser(getCurrenUserName());
        spdBestSellerAdvertisementForm.setModifyUser(getCurrenUserName());
        SpdBestSellerAdvertisementVo spdBestSellerAdvertisementVo = new SpdBestSellerAdvertisementVo();
        BeanUtilsHelper.copyProperties(spdBestSellerAdvertisementForm, spdBestSellerAdvertisementVo);
        //执行新建或者更新操作
        ResultDto result = spdBestSellerAdvertisementApi.save(spdBestSellerAdvertisementVo);

        if (!result.getSuccess()) {
            logger.businessTrail("保存导航广告信息", "保存导航热卖广告失败", result.getMessage());
        }
        return result;
    }



 /**
     * 保存广告图片到远程服务器
     * @author wangliang
     * @param multipartFile
     * @return
     */
    public String saveImageRomate(MultipartFile multipartFile) {
        logger.runTrail("保存导航热卖广告的图片", "saveImageRomate", multipartFile);
        ImageUploadModal model = new ImageUploadModal();
        model.setAccessKey("admin!749ac63ea74249afbc4fb9f7204a2105");
        model.setDirPublic("$images");
        model.setImageServerHost("http://img.healthcareol.com:10000");
        List upload = new ArrayList();
        try {
            upload = model.upload(multipartFile);
        } catch (Exception e) {
            LoggerUtil.getLogger().error("导航热卖广告图片保存", e);
        }

        return upload.get(0);
    }


图片上传到远程服务器处理类

package com.redmanor.common2c.common.web.model;

import java.io.ByteArrayInputStream;
import java.io.File;
import java.io.IOException;
import java.net.URLDecoder;
import java.net.URLEncoder;
import java.nio.charset.Charset;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;

import org.apache.commons.lang3.StringUtils;
import org.apache.http.HttpEntity;
import org.apache.http.HttpResponse;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.entity.ContentType;
import org.apache.http.entity.mime.MultipartEntityBuilder;
import org.apache.http.impl.client.CloseableHttpClient;
import org.apache.http.impl.client.HttpClients;
import org.apache.http.util.EntityUtils;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Component;
import org.springframework.web.multipart.MultipartFile;

import cn.com.dhc.fw.log4j2.Logger;

import com.alibaba.fastjson.JSONObject;
import com.alibaba.fastjson.util.Base64;

@Component
public class ImageUploadModal {

    /**
     * //日志组件
     */
    protected Logger logger = Logger.getLogger(ImageUploadModal.class);

    @Value("${IMAGE_SERVER_HOST}")
    private String   imageServerHost;

    @Value("${IMAGE_SERVER_PUBLIC_DIR}")
    private String   dirPublic;

    @Value("${IMAGE_SERVER_ACCESS_KEY}")
    private String   accessKey;
    //
    //
    @Value("${IMAGE_SERVER_GOODS}")
    private String   dirGood;

    /**
     * 店铺
     */
    @Value("${IMAGE_SERVER_STORE}")
    private String   dirStore;

    public void setImageServerHost(String imageServerHost) {
        this.imageServerHost = imageServerHost;
    }

    //    @Value("${IMAGE_SERVER_ADMIN_KEY}")
    //    private String DIR_GOOD;

    //
    // @Value("${IMAGE_SERVER_ADMIN_KEY}")
    // private String DIR_GOOD ;
    //

    public void setDirPublic(String dirPublic) {
        this.dirPublic = dirPublic;
    }

    public void setAccessKey(String accessKey) {
        this.accessKey = accessKey;
    }

    // api/get_access_key?bucketName=fzxs

    /**
     * 申請認證
     *
     * @param name
     * @return
     * @throws Exception
     */
    public final String getAccessKey(String name) throws Exception {

        logger.businessTrail("图片上传", "申请图片密码", name);

        if (StringUtils.isEmpty(name)) {
            return null;
        }

        try (CloseableHttpClient clients = HttpClients.createDefault()) {

            logger.businessTrail("图片上传", "图片服务器路径", name);

            HttpGet get = new HttpGet(imageServerHost + "/api/get_access_key?bucketName=" + name);

            HttpResponse response = clients.execute(get);

            int code = response.getStatusLine().getStatusCode();

            if (code != 200) {

                return null;
            }

            HttpEntity entity = response.getEntity();

            String addr = EntityUtils.toString(entity, Charset.forName("UTF-8"));

            JSONObject json = JSONObject.parseObject(addr);

            if (json.getBoolean("success")) {
                return json.getString("accessKey");
            }

            return null;

        }

    }

    /**
     * @param files
     * @return
     * @throws Exception
     */
    public final List upload(MultipartFile... files) throws Exception {

        return upload(accessKey, files);
    }

    public final List upload(String accessKey, MultipartFile... files) throws Exception {

        return upload1(accessKey, "", files);
    }

    /**
     * http://img.zhenao.com/upload?accessKey=admin!749
     * ac63ea74249afbc4fb9f7204a2105
     *
     * @param accessKey
     * @param files
     * @return
     * @throws IOException
     */
    public final List upload1(String accessKey, String path, MultipartFile... files) throws Exception {

        List address = new ArrayList<>();

        if (files == null || files.length == 0) {
            return address;
        }

        for (MultipartFile file : files) {

            try (CloseableHttpClient clients = HttpClients.createDefault()) {

                logger.businessTrail("图片上传", "图片服务器路径", imageServerHost);

                HttpPost post = new HttpPost(imageServerHost + (StringUtils.isEmpty(path) ? "/upload" : "/upload/ftp")
                                             + "?accessKey=" + accessKey);

                MultipartEntityBuilder reqEntity = MultipartEntityBuilder.create();

                logger.businessTrail("图片上传", "图片类型", file.getContentType());

                logger.businessTrail("图片上传", "图片名称", file.getOriginalFilename());

                reqEntity.addBinaryBody("file", file.getInputStream(), ContentType.create(file.getContentType()),

                URLEncoder.encode(file.getOriginalFilename(), "UTF8"))

                .addTextBody("return", "string")

                .addTextBody("path", URLEncoder.encode(path,"UTF8"));

                post.setEntity(reqEntity.build());

                HttpResponse response = clients.execute(post);

                int code = response.getStatusLine().getStatusCode();

                logger.businessTrail("图片上传", "状态:", code);

                if (code != 200) {
                    continue;
                }
                HttpEntity entity = response.getEntity();

                String addr = EntityUtils.toString(entity, Charset.forName("UTF-8"));

                //                addr = URLDecoder.decode(addr,"UTF8");

                //                address.add(addr.replaceAll("\\\\", "/"));
                address.addAll(Arrays.asList(addr.replaceAll("\\\\", "/").split(",")));
            }
        }
        return address;
    }

    public final String upload(File files, String dir, String contentType) throws Exception {

        String address = null;

        if (files == null || files.length() == 0) {
            return address;
        }

        try (CloseableHttpClient clients = HttpClients.createDefault()) {

            logger.businessTrail("图片上传", "图片服务器路径", imageServerHost);

            HttpPost post = new HttpPost(imageServerHost + "/upload?accessKey=" + accessKey);

            MultipartEntityBuilder reqEntity = MultipartEntityBuilder.create();

            logger.businessTrail("图片上传", "图片类型", contentType);

            logger.businessTrail("图片上传", "图片名称", files.getName());

            reqEntity.addBinaryBody("file", files, ContentType.create(contentType), files.getName())

            .addTextBody("return", "string")

            .addTextBody("dir", dir);

            post.setEntity(reqEntity.build());

            HttpResponse response = clients.execute(post);

            int code = response.getStatusLine().getStatusCode();

            logger.businessTrail("图片上传", "状态:", code);

            if (code != 200) {
                return address;
            }
            HttpEntity entity = response.getEntity();

            String addr = EntityUtils.toString(entity, Charset.forName("UTF-8")).replaceAll("\\\\", "/");

            return addr;
        }
    }

    /**
     * 上传文件
     *
     * @param urls
     * @return
     * @throws IOException
     */
    public final List upload(String dir, String... urls) throws Exception {

        // img.zhenao.com/public/admin/2015/12/4/487eadad2875224ed54a2d67bc428ac9.jpg

        logger.businessTrail("图片上传", "图片服务器路径", imageServerHost);

        List address = new ArrayList<>();

        if (urls == null || urls.length == 0) {
            return address;
        }

        try (CloseableHttpClient clients = HttpClients.createDefault()) {

            StringBuilder _sb = new StringBuilder();

            for (String url : urls) {
                _sb.append("&urls=" + url);
            }
            HttpPost get = new HttpPost(imageServerHost + "/upload/save?savedir=" + dir + "&return=string&accessKey="
                                        + accessKey + _sb.toString());

            HttpResponse response = clients.execute(get);

            int code = response.getStatusLine().getStatusCode();

            if (code != 200) {
                return address;
            }

            HttpEntity entity = response.getEntity();

            String addr = EntityUtils.toString(entity, Charset.forName("UTF-8"));

            address.addAll(Arrays.asList(addr.replaceAll("\\\\", "/").split(",")));

        }
        return address;

    }

    /**
     * 上传文件
     *
     * @param base64
     * @param fileName
     * @return
     * @throws IOException
     */
    public final List uploadAsBase64(String dic, String base64, String fileName) throws Exception {

        logger.businessTrail("图片上传", "图片服务器路径", imageServerHost);

        List address = new ArrayList<>();

        if (base64 == null || base64.length() == 0) {
            return address;
        }

        try (CloseableHttpClient clients = HttpClients.createDefault()) {

            logger.businessTrail("图片上传", "图片服务器路径", imageServerHost);

            HttpPost post = new HttpPost(imageServerHost + "/upload?accessKey=" + accessKey);

            MultipartEntityBuilder reqEntity = MultipartEntityBuilder.create();

            //                {"file":"data:image/jpeg;base64,/9j/4AAQSkZJRgABAgEAYABgAAD

            if (!base64.startsWith("data:image")) {

                logger.businessTrail("图片上传", "图片类型", "错误的数据类型");

                return address;
            }

            String contentType = base64.substring(base64.indexOf(":") + 1, base64.indexOf(";"));

            String encode = base64.substring(base64.indexOf(";") + 1, base64.indexOf(","));

            if (!StringUtils.equals(encode, "base64")) {

                logger.businessTrail("图片上传", "图片类型", "错误的数据编码 不是 base64");

                return address;
            }

            byte[] bytes = Base64.decodeFast(base64.substring(base64.indexOf(",") + 1));

            ByteArrayInputStream inputStream = new ByteArrayInputStream(bytes);

            logger.businessTrail("图片上传", "图片类型", contentType);

            logger.businessTrail("图片上传", "图片名称", fileName);

            reqEntity.addBinaryBody("file", inputStream, ContentType.create(contentType), fileName)

            .addTextBody("return", "string");

            post.setEntity(reqEntity.build());

            HttpResponse response = clients.execute(post);

            int code = response.getStatusLine().getStatusCode();

            logger.businessTrail("图片上传", "状态:", code);

            if (code != 200) {

                return address;
            }
            HttpEntity entity = response.getEntity();

            String addr = EntityUtils.toString(entity, Charset.forName("UTF-8")).replaceAll("\\\\", "/");

            address.add(addr);
        }
        return address;

    }

}

ajaxfileupload.js插件地址

你可能感兴趣的:(Java开发,Spring开发,jQuery,前端页面技术)