【uploadify】使用Uploadify+SpringMVC实现不用From文件页面无刷上传

5 篇文章 0 订阅
1 篇文章 0 订阅

1、uploadify官网下载jquery.uploadify.min.js

网址http://www.uploadify.com/下载最新版本的uploadify
文件目录如下图:
文件目录
1:min.js文件;
2:取消上传用的X号图片;
3:样式css,可以实现下图样式:
demo
4:swf文件。

2、JSP页面

<%@ page language="java" contentType="text/html; charset=UTF-8"
    pageEncoding="UTF-8"%>
<%@ taglib uri="http://java.sun.com/jsp/jstl/core" prefix="c"%>
<html>
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>upload</title>

<link rel="stylesheet" type="text/css" href="${CONTEXT_PATH}/statics/css/jeasyui/themes/default/easyui.css">
<link rel="stylesheet" href="${CONTEXT_PATH}/statics/css/uploadify.css">

<script type="text/javascript" src="${CONTEXT_PATH}/statics/js/jquery.min.js"></script>
<script type="text/javascript" src="${CONTEXT_PATH}/statics/js/jeasyui/jquery.easyui.min.js"></script>
<script type="text/javascript" src="${CONTEXT_PATH}/statics/js/uploadify/jquery.uploadify.min.js"></script>

</head>
    <body>
    <table border="1">
        <tr>
            <td style="width: 10%;">附件上传:</td>
            <td>
                <table class="table table-bordered" border="1">
                    <tbody class="fileUploadTable">
                    </tbody>
                </table>
                <input type="file" id="uploadify">
                <div style="margin-left: 28px;margin-top: -15px">
                    <span style="color: red; font-size: 5px">*文件不得超过20M</span>
                    <input class="fileList" value="" /> 
                </div>
            </td>
        </tr>
    </table>
        <script type="text/javascript">
        $(function () {
            if($("#uploadify")){
                $("#uploadify").uploadify({
                    //指定swf文件
                    'swf': '${CONTEXT_PATH}/statics/js/uploadify/uploadify.swf',
                    //后台处理的页面
                    'uploader': '${pageContext.request.contextPath }/file/upload',
                    //按钮显示的文字
                    'buttonText': '选择文件',
                    //设置按钮样式
                    'buttonClass': 'fileLists',
                    //上传文件的类型  默认为所有文件    'All Files'  ;  '*.*'
                    //在浏览窗口底部的文件类型下拉菜单中显示的文本
                    'fileTypeDesc': 'All Files',
                    //允许上传的文件后缀
                    'fileTypeExts': '*.*',
                    //上传队列
                    'queueID': false,
                    //文件上传大小限制20M
                    'fileSizeLimit': '20480',
                    //上传文件速度
                    'progressData': 'percentage',
                    //上传成功的方法
                    onUploadSuccess: function(file,data){

                        var fileObj = JSON.parse(data); 

                        var tableHtml = "<tr width='220px' class='FILEID'><td width='100px'><a href='FILEPATH'>FILENAME</a></td><td width='80px'>FILEDATE</td><td width='40px'><a href='javascript:FILEMETHOD'>删除</a></td></tr>"

                        var fileName = fileObj.fileName + "";

                        var cancleMethod = "cancelUpload(" + '"' + fileObj.fileId + '"' + ");";

                        tableHtml = tableHtml.replace("FILENAME",fileName).replace("FILEDATE",fileObj.fileDate).replace("FILEMETHOD",cancleMethod).replace("FILEPATH", fileObj.filePath).replace("FILEID", fileObj.fileId);

                        $(".fileUploadTable").append(tableHtml);

                        $(".fileList").attr("value",$(".fileList").val() + fileObj.filePath + ";" );//填充内容 

                    },
                    //选择文件后自动上传
                    'auto': true,
                    //设置为true将允许多文件上传
                    'multi': false
                });
            }

        });

        function cancelUpload(id){
            $.ajax({
                type: 'POST',
                url: '${pageContext.request.contextPath }/file/cancel',
                data: {fileId : id},
                success: function(data){
                    $("." + id).text("");
                    //去掉放在隐藏input中的值
                    var newInputVal = "";
                    var inputVals = $(".fileList").val().split(';');
                    for(i in inputVals){
                        if(inputVals[i].indexOf(id)){
                            //不进行任何操作
                        }else{
                            newInputVal = inputVals[i] + ";";
                        }
                    }
                $(".fileList").attr("value",newInputVal);//填充内容 
                },
            });
        }
    </script></html>

3、Controller文件

import java.io.File;
import java.io.IOException;
import java.io.Writer;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.HashMap;
import java.util.Map;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

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.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.multipart.MultipartFile;
import org.springframework.web.multipart.MultipartHttpServletRequest;

import com.asiainfo.common.util.PropertyReader;
import com.asiainfo.dao.entity.AFUser;
import com.asiainfo.service.interfaces.IUserSessionSrv;
import com.google.gson.Gson;

/**
 * 
 * @author tanglei
 * 文件上传
 */
@Controller
@RequestMapping("/file")
public class UploadController {

    private static final Log logger = LogFactory.getLog(UploadController.class);

    @Autowired
    private IUserSessionSrv userSessionSrv; 

    /**
     * 上传方法
     * @param request
     * @param response
     * @throws IOException
     */
    @RequestMapping(value = "/upload", method = { RequestMethod.POST })
    public void uploadFile(HttpServletRequest request, HttpServletResponse response) throws IOException {

        //获取用户信息
        AFUser user = userSessionSrv.getUserSessionInfo(request, response).getUser();

        //获取上传文件
        MultipartHttpServletRequest multipartRequest = (MultipartHttpServletRequest) request;
        MultipartFile file = multipartRequest.getFile("Filedata");
        //可传入存储位置
        String time = new Date().getTime() + "";
        String path = "";
        if(user == null){
            path = PropertyReader.getProperty("user_upload_path") + "text" + "_" + "1024" + "/" + time;
        }else{
            path = PropertyReader.getProperty("user_upload_path") + user.getName() + "_" + user.getId() + "/" + time;
        }
        //file:上传上来的文件
        //uploadFile:文件存储位置
        //targetFile:重命名后的文件
        File uploadFile = new File(path);
        if (!uploadFile.exists()) {
            uploadFile.mkdirs();
        }
        //原文件名
        String originalFilename = file.getOriginalFilename();
        File targetFile = new File(path,originalFilename);

        //保存
        try {
            file.transferTo(targetFile);
        } catch (Exception e) {
            logger.error("Transfer File Error");
        }
        Gson gson = new Gson();

        Map<String,String> result = new HashMap<String,String>();
        result.put("fileName", targetFile.getName());
        result.put("fileDate", new SimpleDateFormat("yyyy-MM-dd hh:mm:ss").format(new Date()));
        result.put("filePath", targetFile.getPath());
        result.put("fileId", time);

        String res = gson.toJson(result);
        Writer writer = response.getWriter();
        writer.write(res);
        writer.close();
    }

    /**
     * 取消上传,并删除服务器文件
     * @param request
     * @param response
     * @throws IOException
     */
    @RequestMapping(value = "/cancel", method = { RequestMethod.POST })
    public void cancelUploadFile(@RequestParam String fileId, HttpServletRequest request, HttpServletResponse response) throws IOException {

        //获取用户信息
        AFUser user = userSessionSrv.getUserSessionInfo(request, response).getUser();

        String path = "";
        if(user == null){
            path = PropertyReader.getProperty("user_upload_path") + "text" + "_" + "1024" + "/";
        }else{
            path = PropertyReader.getProperty("user_upload_path") + user.getName() + "_" + user.getId() + "/";
        }

        File targetFile = new File(path + fileId);

        Writer writer = response.getWriter();
        //删除
        if (targetFile.exists()) {
            //声明目录下所有的文件 files[];  
            File[] files = targetFile.listFiles();
            for (File f : files) {
                f.delete();
            };
            //删除文件夹  
            targetFile.delete();
            logger.debug("file:" + targetFile + " is deleted");
            writer.write("success");
        } else {
            writer.write("file not exists");
        }
        writer.close();
    }
}
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值