您的位置:首页 > 编程语言 > Java开发

webuploader

2016-04-29 17:52 399 查看
server.xml 配置

<Context docBase="D:\\uploads" path="/images" reloadable="false"/>

<%@ page language="java" import="java.util.*" pageEncoding="UTF-8" %>

<%@ taglib uri="http://java.sun.com/jsp/jstl/core" prefix="c" %>

<%String ctx = request.getContextPath();%>

<script type="text/javascript" src="<%=request.getContextPath()%>/webUpload/webuploader.min.js"></script>

<link rel="stylesheet" type="text/css" href="<%=request.getContextPath()%>/webUpload/webuploader.css">

<script type="text/javascript" src="<%=ctx%>/views/executive/addExecNext.js"></script>

<div id="contact-form" style="padding:10px 20px 20px;">

    <form id="execForm" method="post">

     <input type="hidden" id="executiveContent" name="executiveContent" />

        <div class="mb-10">

            <div class="ipt-w-c">

                <input class="ipt-text" id="executiveTitle" type="text" value="" name="executiveTitle" placeholder="标题" maxLength="20">

            </div>

            <input type="hidden" id="executiveDescribe" name="executiveDescribe" value="<%=request.getParameter("executiveDescribe") %>">

            <input type="hidden" id="executivePriority" name="executivePriority" value="<%=request.getParameter("execPriority") %>">

            <input type="hidden" id="approvalUserId" name="approvalUserId" value="<%=request.getParameter("approUserId") %>">

            <input type="hidden" id="receiveUserId" name="receiveUserId" value="<%=request.getParameter("recUserId") %>">

        </div>

        <div class="mb-10" style="height: 220px; overflow: auto;">

            <div style="width: 550px;">

                <script id="executiveContentTxt" type="text/plain"></script>

            </div>

        </div>

        

<div id="uploadNews">

    

    <form id="AddclassTeachingList" name="AddclassTeachingList" method="post">

        

        <div class="hf">

            <span class="fl icon-photo mr-20" id="imgPicker">添加图片</span>

            <span class="fl icon-enclosure" id="filePicker">添加附件</span>

        </div>

        

        <!-- 图片列表 -->

        <div class="hf text-pic-box uploader-list" id="imgList"></div>

        <!-- 文件列表 -->

        <div class="hf add-fj-ul" style="padding-top: 20px;" id="fileList"></div>

        

        <textarea class="none" name="totalPicPath" id="totalPicPath"></textarea>

        <textarea class="none" name="totalFilePath" id="totalFilePath"></textarea>

    

    </form>

</div>

        

        <div class="hf">

            <!-- <input class="fl" id="sendChk" name="sendChk" value="" type="checkbox">

             <label class="fl" for="sendChk">同时发送互联通知</label>

             <span class="jqTransformCheckboxWrapper">

                 <span class="jqTransformCheckbox" id="ck_send" onclick="selfCheckBox('ck_send','sendChk');"></span>

                 <input id="isSend" name="isSend" value="" type="hidden">

             </span>-->

            <b class="fr btn-done-circle" onclick="saveExec();"></b>

        </div>

    

    </form>

</div>

<script>

    /* ud编辑框 start */

    var editor = UE.getEditor('executiveContentTxt', { maximumWords: 500 });

</script>

<script type="text/javascript">

    $(function(){

        //加载图片上传方法

        loadImageKj();

        //加载文件上传方法

        loadFileKj();

    });

    /**

     * 提交form表单

     */

    function fileOrImgInfo(){

        

        //图片附件赋值

        var imgs = "";

        var a = $("#imgList").find("ol");

        for (var j = 0; j < a.length; j++) {

            imgs += a.eq(j).attr("data-value") + ",";

        }

        $("#totalPicPath").val(subFun(imgs));

        

        //文件附件赋值

        var files = "";

        var a = $("#fileList").find("li");

        for (var j = 0; j < a.length; j++) {

            files += a.eq(j).attr("data-value") + ";";

        }

        $("#totalFilePath").val(subFun(files));

    }

    var subFun = function(str){

        return str.substring(0, str.length - 1);

    }

    /**

     * 加载图片上传控件

     */

    function loadImageKj(){

        var uploader = WebUploader.create({

            // 选完图片后,是否自动上传。

            auto: true,

            // swf图片路径

            swf: 'webUpload/Uploader.swf',

            // 文件接收服务端。

            server: ctx + '/fileorimgupload/uploadImg',

            // 选择文件的按钮。可选。

            // 内部根据当前运行是创建,可能是input元素,也可能是flash.

            pick: '#imgPicker',

            fileNumLimit: 8,

            // 只允许选择图片文件。

            accept: {

                title: 'Images',

                extensions: 'jpg,jpeg,bmp,gif,png',

                mimeTypes: 'image/*'

            }

        });

        // 图片上传成功,给item添加成功class, 用样式标记上传成功。

        uploader.on('uploadSuccess', function(file, response){

            $('#' + file.id).addClass('upload-state-done');

            var obj = JSON.parse(response._raw);

            console.log(obj.picName);

            console.log(obj.picUrl);

            var

                html = '<ol class="text-pic-ol" style="position: relative;overflow: visible;" data-value=\"' + response._raw + '\">' +

                  /*   '<img class="baseImg" style="" src="' + ctx + '/uploads/s/' + response._raw + '">' + */

                    '<img class="baseImg" style="" src="' +obj.picUrl+obj.picName + '">' +

                    '<span class="btnDel del-red-btn" dataVal="' + response._raw + '" >' +

                    '<img src="' + ctx + '/styles/img/xh-img/cuo.png" class="schintrimg cur" style="width:16px;height:16px;"></span>' +

                    '</ol>',

                $li = $(html),

                $btnClose = $li.find("span.btnDel");

            

            $btnClose.click(function(){

                $btnClose.parent().remove();

                uploader.removeFile(file, true);

                doService("fileorimgupload/delImg", "img", $btnClose.attr("dataVal"));

            });

            

            // $list为容器jQuery实例

            $("#imgList").prepend($li);

        });

        

        // 图片上传失败,显示上传出错。

        uploader.on('uploadError', function(file){

            var $li = $('#' + file.id), $error = $li.find('div.error');

            // 避免重复创建

            if (!$error.length) {

                $error = $('<div class="error"></div>').appendTo($li);

            }

            $error.text('上传失败');

        });

        

        // 完成上传完了,成功或者失败,先删除进度条。

        uploader.on('uploadComplete', function(file){

            $('#' + file.id).find('.progress').remove();

        });

    }

    

    //加载文件上传控件

    function loadFileKj(){

        var uploader = WebUploader.create({

            // 选完文件后,是否自动上传。

            auto: true,

            // 不压缩image

            resize: false,

            // swf文件路径

            swf: ctx + 'webUpload/Uploader.swf',

            // 文件接收服务端。

            server: ctx + '/fileorimgupload/fileUpload',

            // 选择文件的按钮。可选。

            pick: {

                id: '#filePicker',

                label: '添加附件'

            },

            fileNumLimit: 5,

            // 只允许选择图片文件。

            accept: {

                title: 'Files',

                extensions: 'zip,rar,xls,xlsx,ppt,pptx,docx,doc,txt',

                mimeTypes: 'application/.xls,.xls,.xlsx,.doc,.docx,.ppt,.pptx,.zip,.rar,.txt'

            }

        });

        

        // 文件上传过程中创建进度条实时显示。

        uploader.on('uploadProgress', function(file, percentage){

            var $li = $('#' + file.id),

                $percent = $li.find('.progress .progress-bar');

            // 避免重复创建

            if (!$percent.length) {

                $percent = $('<div class="progress progress-striped active">' +

                    '<div class="progress-bar" role="progressbar" style="width: 0%">' +

                    '</div>' +

                    '</div>').appendTo($li).find('.progress-bar');

            }

            $li.find('p.state').text('上传中');

            $percent.css('width', percentage * 100 + '%');

        });

        

        uploader.on('uploadSuccess', function(file, response){

            $('#' + file.id).find('p.state').text('已上传');

            console.log(response._raw);

            debugger;

            

            var backName = response._raw;

            var $li = $(

                    '<li class="add-fj-li fl pl-10" data-value=\"' + backName + '\">' +

                    '<img src="' + getFileIoc(backName.split(",")[0]) + '"\">' + backName.split(",")[0] +

                    '<a target=\"_blank\" class=\"btnDel add-fj-del\" dataVal="' + backName.split(",")[1] + '" title=\"删除\"></a>' +

                    '</li>'

                ),

                $btnClose = $li.find("a.btnDel");

            

            $btnClose.click(function(){

                $btnClose.parent().remove();

                uploader.removeFile(file);

                doService("fileorimgupload/delFile", "attFile", $btnClose.attr("dataVal"));

            });

            

            // $list为容器jQuery实例

            $("#fileList").prepend($li);

        });

        

        uploader.on('uploadError', function(file, reason){

            $('#' + file.id).find('p.state').text('上传出错');

        });

        

        uploader.on('uploadComplete', function(file){

            $('#' + file.id).find('.progress').fadeOut();

        });

    }

    //根据文件后缀赋值图标

    var getFileIoc = function(fileName){

        var imgIoc = ctx + "/styles/img/login/xz-7.png";

        var iocName = fileName.substring(fileName.lastIndexOf(".") + 1, fileName.length);

        if (iocName == "zip" || iocName == "rar") {

            imgIoc = ctx + "/styles/img/login/xz-9.png";

        } else if (iocName == "xlsx" || iocName == "xls") {

            imgIoc = ctx + "/styles/img/login/xz-6.png";

        } else if (iocName == "docx" || iocName == "doc") {

            imgIoc = ctx + "/styles/img/login/xz-2.png";

        } else if (iocName == "pptx" || iocName == "ppt") {

            imgIoc = ctx + "/styles/img/login/xz-3.png";

        }

        return imgIoc;

    }

</script>

java code as follows:

package com.wd.interconnect.controllers;

import java.io.File;

import java.io.IOException;

import java.io.PrintWriter;

import java.text.SimpleDateFormat;

import java.util.Date;

import java.util.HashMap;

import java.util.Map;

import javax.servlet.http.HttpServletRequest;

import org.apache.commons.fileupload.disk.DiskFileItem;

import org.springframework.beans.factory.annotation.Autowired;

import org.springframework.web.multipart.MultipartFile;

import org.springframework.web.multipart.commons.CommonsMultipartFile;

import com.alibaba.fastjson.JSON;

import com.wd.base.controllers.BaseController;

import com.wd.common.utils.ConfigUtil;

import com.wd.common.utils.FileUtils;

import com.wd.common.utils.ImageUtils;

import com.wd.common.utils.StringUtils;

import com.wd.interconnect.service.FileOrImgUploadService;

import net.paoding.rose.web.Invocation;

import net.paoding.rose.web.annotation.Param;

import net.paoding.rose.web.annotation.Path;

import net.paoding.rose.web.annotation.rest.Post;

/**

 * 文件图片上传

 */

@Path("fileorimgupload")

public class FileOrImgUploadController extends BaseController{

@Autowired

private FileOrImgUploadService uploadService;

/**

     * webuploader 上传图片

     * 

     * 

     */

    @Post("uploadImg")

    public void uploadImages(final Invocation inv,MultipartFile[] files,@Param("typeName")String typeName) throws IOException {

     this.changeDBS(inv.getRequest());

String path = ConfigUtil.getProperty("filePath");

        for (MultipartFile file : files) {

            String suffix = file.getOriginalFilename().substring(file.getOriginalFilename().lastIndexOf(".") + 1);

            //新文件名生成

String now = new SimpleDateFormat("yyyyMMddHHmmss").format(new Date());

            String reTime = typeName + "_" + now+StringUtils.getRandom();

            //大中小图存放地址

            String bigImagePath = path + "/b/";

            String middleImagePath = path +"/m/";

            String smallImagePath = path + "/s/";

            FileUtils.makeSureFolderExits(bigImagePath);

            FileUtils.makeSureFolderExits(middleImagePath);

            FileUtils.makeSureFolderExits(smallImagePath);

            CommonsMultipartFile cf = (CommonsMultipartFile) file;

            DiskFileItem fi = (DiskFileItem) cf.getFileItem();

            File f = fi.getStoreLocation();

            

            ImageUtils imageUtils = new ImageUtils(f);

            

            String picName = reTime + "." + suffix;

            String picUrl = getPhotoUrl(inv) +"s/";

            Map<String, Object> map = new HashMap<String, Object>();

            

            System.out.println(picName);

            System.out.println("----------------");

            System.out.println(picUrl);

            

            map.put("picName", picName);

            map.put("picUrl", picUrl);

            

            

            

            System.out.println(smallImagePath + picName);

            System.out.println(middleImagePath + picName);

            System.out.println(bigImagePath + picName);

            

            imageUtils.resize(64, 64, smallImagePath + picName);

            imageUtils.resize(126, 88, middleImagePath + picName);

            imageUtils.resizeByWidth(480, bigImagePath + picName);

            PrintWriter out = inv.getResponse().getWriter();

            out.write( JSON.toJSONString(map));

            

        }

    }

    /**

     * 删除图片

     * @param invocation

     * 

     * 

     */

    @Post("delImg")

    public void deleteImg(final Invocation inv){

     this.changeDBS(inv.getRequest());

String path = ConfigUtil.getProperty("filePath");

        String img = inv.getRequest().getParameter("img");

        String bigImagePath = path + "/b/";

        String middleImagePath = path +"/m/";

        String smallImagePath = path + "/s/";

        File file2 = new File(bigImagePath+img);

        if (file2.exists() && file2.isFile()) {

            file2.delete();

        }

        File file3 = new File(middleImagePath+img);

        if(file3.exists() && file3.isFile()){

            file3.delete();

        }

        File file1 = new File(smallImagePath+img);

        if (file1.exists() && file1.isFile()) {

            file1.delete();

        }

    }

/**

 * 附件上传

 * 

 * 

 */

    @Post("fileUpload")

    public void uploadFiles(final Invocation inv,MultipartFile[] files,@Param("typeName")String typeName) throws IOException {

     this.changeDBS(inv.getRequest());

inv.getRequest().setCharacterEncoding("UTF-8");

String path = ConfigUtil.getProperty("filePath");

        String attachPath = path + "/attachFile/";

        for (MultipartFile file : files) {

         // 原文件名

String t_name = file.getOriginalFilename();

         // 获取文件后缀

            String suffix = file.getOriginalFilename().substring(file.getOriginalFilename().lastIndexOf(".") + 1);

            //新文件名生成

String now = new SimpleDateFormat("yyyyMMddHHmmss").format(new Date());

            String reTime = typeName + "_" + now+StringUtils.getRandom();

            FileUtils.makeSureFolderExits(attachPath);

            String fileName = reTime +"."+suffix;

            File destFile = new File(attachPath+"/"+fileName);

            file.transferTo(destFile);

            inv.getResponse().setCharacterEncoding("UTF-8");

            PrintWriter out = inv.getResponse().getWriter();

            out.write(t_name+","+fileName);

        }

    }

    

    /**

     * 删除附件 

     * @param inv

     */

    @Post("delFile")

    public void deleteFiles(final Invocation inv){

     this.changeDBS(inv.getRequest());

String path = ConfigUtil.getProperty("filePath");

        String files = inv.getRequest().getParameter("attFile");

        String attachPath = path + "/attachFile/";

        

        File file = new File(attachPath+files);

        if (file.exists() && file.isFile()) {

            file.delete();

        }

    }

    /**

     * 获取图片路径

     * @param inv

     * @return

     */

    private String getPhotoUrl(Invocation inv){

String host = inv.getRequest().getHeader("host");

     String contextPath = ConfigUtil.getProperty("photoUrl");

host += contextPath;

return "http://"+host;

}

}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签:  java