首页 > 代码库 > springmvc+uploadify3.2.1完整代码示例,java,jsp

springmvc+uploadify3.2.1完整代码示例,java,jsp

  1. 前台页面: 引入js和css
<script type="text/javascript" src="http://www.mamicode.com/${STATIC_FILE_PATH}/js/jquery/jquery-1.10.js${STATIC_FILE_VERSION}"></script> <link type="text/css" rel="stylesheet" href="http://www.mamicode.com/${STATIC_FILE_PATH}/js/jPlug/uploadify/uploadify.css${STATIC_FILE_VERSION}"></link>

<script type="text/javascript" src="http://www.mamicode.com/${STATIC_FILE_PATH}/js/jPlug/uploadify/jquery.uploadify.min.js${STATIC_FILE_VERSION}"></script>:

2:脚本内容:

如下参数你还没搞懂的话 ,请查阅官方文档,地址:http://www.uploadify.com/documentation/

<script type="text/javascript">
$(document).ready(function(){
    $(function() {
        $(‘#file_upload‘).uploadify({
            ‘swf‘      : ‘${STATIC_FILE_PATH}/js/jPlug/uploadify/uploadify.swf‘,
            ‘uploader‘ : ‘${CONTEXT_PATH}/shop/upload.html‘,
            ‘height‘: 25,
            ‘whith‘ :120,
            ‘auto‘  : false,
            ‘fileDataName‘:‘file‘,
            ‘buttonText‘ : ‘选择图片...‘,
            ‘fileTypeExts‘ : ‘*.gif; *.jpg; *.png‘,
            ‘multi‘    : false,
            ‘method‘   :‘post‘,
            ‘debug‘:true,
            ‘onUploadSuccess‘ : function(file, data, response) {
                 alert(‘The file ‘ + file.name + ‘ was successfully uploaded with a response of ‘ + response + ‘:‘ + data);
            },
            ‘onUploadError‘ : function(file, errorCode, errorMsg, errorString) {
                alert(‘The file ‘ + file.name + ‘ could not be uploaded: ‘ + errorString);
               }
        });
    });
});
</script>

2:<body>内容:

<body >
          <input id="file_upload" type="file" name="file"/>
           <a href="javascript:$(‘#file_upload‘).uploadify(‘upload‘, ‘*‘)">上传文件</a> | <a href="javascript:$(‘#file_upload‘).uploadify(‘stop‘)">停止上传!</a>  
</body>

3:后台controller:

@RequestMapping(value = "http://www.mamicode.com/shop/upload",method=RequestMethod.POST)
    @ResponseBody
    public Object uploadHandlerForUploadify(String picHref,HttpServletRequest request)
            throws Exception {
        Integer userID = 0;
        MultipartHttpServletRequest multipartRequest = (MultipartHttpServletRequest) request;
        MultipartFile multipartFile = multipartRequest.getFile("Filedata");
        /** 写文件前先读出图片原始高宽 **/
        byte[] bytes = multipartFile.getBytes();
        InputStream is = new ByteArrayInputStream(bytes);
        int width = 0; // 原始图片宽
        int height = 0; // 原始图片高
        try {
            BufferedImage bufimg = ImageIO.read(is);
            // 只有图片才获取高宽
            if (bufimg != null) {
                width = bufimg.getWidth();
                height = bufimg.getHeight();
            }
            is.close();
        } catch (Exception e) {
            e.printStackTrace();
            loger.error(e.getMessage());
            is.close();
            throw new Exception("uploadify上传图片读取图片高宽时发生异常!");
        }

        /** 拼成完整的文件保存路径加文件 **/
        String originalFilename = multipartFile.getOriginalFilename(); // 文件全名
        String suffix = StringUtil.substringAfter(originalFilename, "."); // 后缀
        // 文件名转码
        // fileName = Base64.StringToBase64(fileName);
        // fileName = StringUtil.join(fileName, suffix);
        UploadFilePathVO uploadFile = UploadFilePathUtil.initFileUpload(userID, "test", suffix, width, height);
        File file = new File(uploadFile.getRealPath());
        multipartFile.transferTo(file);

    return uploadFile;
    }


4:自定义的上传路径工具类:

/**
     * 获取图片上传路径(处理高宽)
     *
     * @return
     */
    public static UploadFilePathVO initFileUpload(Integer userID, String imageType, String suffix, int width, int height) {
        String randomKey = RandomUtil.getRandomString(6);
        Date date = new Date();
        String dateStr = new SimpleDateFormat("yyyyMMdd").format(date);
        String timeStr = new SimpleDateFormat("HHmmssSSS").format(date);
        int hashcode = Math.abs(userID.hashCode() % 256);

        String relativePath = StringUtil.join(imageType, "/", hashcode, "/", userID, "/", dateStr, "/");
        String realPath = StringUtil.join(Constants.UPLOAD_REALPATH, "/", relativePath);

        File logoSaveFile = new File(realPath);
        if (!logoSaveFile.exists()) {
            logoSaveFile.mkdirs();
        }
        // 图片文件名: 时间戳 + 随机串 + 高宽
        String fileName = StringUtil.join(timeStr, randomKey, ‘_‘, height, ‘_‘, width, ‘.‘, suffix);
        UploadFilePathVO uploadFile = new UploadFilePathVO();
        uploadFile.setRelativePath(StringUtil.join(relativePath, fileName));
        uploadFile.setRealPath(StringUtil.join(realPath, fileName));
        return uploadFile;
    }


5:UploadFilePathVO类:

    public String realPath;
    public String relativePath;
    private int imgHeight; // 上传图片的高
    private int imgWidth; // 宽


springmvc+uploadify3.2.1完整代码示例,java,jsp