uploadify多图片上传(html5版本)

最近在做公司后台,关于项目发布的功能,需求中有多个图片上传的功能。
故查询资料,开发整理如下(之前发过一版flash的,现在将html5整理如下,与之前那篇的差别就是插件参数的不同)。
说明一下:在官网html5版本,是要收费的。

  1. 首先下载相关的外部文件(js,css等)以及案例。
    1、地址:
    付费:http://www.uploadify.com/download/
    不付费:自己找,我是从http://www.cnblogs.com/lvdabao/p/3452858.html 这位朋友这里下载的。
    2、下载之后有用的文件如图:
    uploadify多图片上传(html5版本)_第1张图片

  2. 可以开始在你的项目里进行开发了~~~~

  3. 将必须的文件js,css放入到程序中,位置按照各自的习惯来。
    在页面中引用外部文件如图:
    这里写图片描述

  4. 摘取页面部分代码如下:

<%@ page language="java" contentType="text/html; charset=utf-8" pageEncoding="utf-8"%>
<%@ taglib uri="http://java.sun.com/jsp/jstl/core" prefix="c" %>

<html xmlns="http://www.w3.org/1999/xhtml" xml:lang="en">
<head>
    <meta http-equiv="Content-Type" content="text/html; charset=utf-8"  />
    <title>~~~~~title>
    <script type="text/javascript" src="../../js/jquery.min.js">script>
    <link rel="stylesheet"  type="text/css" href="../../css/uploadify.css" />  
    <script type="text/javascript" src="../../js/swfobject.js">script>  
    <script type="text/javascript" src="../../js/jquery.uploadify.min.js">script>  
<%
        request.setCharacterEncoding("utf-8");
        String path = request.getContextPath();
        String basePath = request.getScheme()+"://"+request.getServerName()+":"+request.getServerPort()+path;
%>
head>
<body>
  <form class="form" action="" method="post">
        <div id="normalHousePublicPart">
                <label>
                        <span class="search-span">公司基础信息(*必选):span> 
                        <input type="hidden" class="simple" id="companyBaseInfo" name="companyBaseInfo"/>
                label>
                 <div class="uploadBox">
                        <div id="uploadfileQueue1" style="padding: 3px;">div>
                        <div id="file_upload1">div>
                        <input type="button" value="上传" onclick="doUpload1()" class="uploadBtn" />
                        <input type="button" value="删除重传公司基础信息" onclick="deleteCompanyInfo1()" class="uploadBtn" />
                        <div id="mypic1" class="uploadImg">div>
                 div>
    form>

    <script type="text/javascript">

        $(function () {  
            $('#file_upload1').uploadifive({
            //开启调试    
           'debug': true ,
           'auto'             : false,
           'buttonText': '选择照片',  
           'formData'         : null,
           'queueSizeLimit': 5,  
             //文件选择后的容器ID    
           'queueID'          : 'uploadfileQueue1',
           'fileObjName':'pic',
           'uploadScript'     : '/manage.onigiri/uploadTestAction/uploadFile',
           'width': '75',  
           'height': '24',
           'multi': true,  
           'fileType':'image/*',
           'fileSizeLimit':'1MB',
           'removeCompleted':'true',
           'onUploadComplete' : function(file, data) {
              $("#mypic1").append("
" />删除
"
); } }); }); //开始上传 function doUpload1() { $('#file_upload1').uploadifive('upload'); } //删除重传 function deleteCompanyInfo1() { $("#mypic1").html(""); } //删除单张 function deleteThisImg(obj){ $(obj).parent("div").remove(); }
script> body> html>

上面是页面中的处理,下面来看一下action中的后台处理。

5.Action中的处理
其中 “CommonsMultipartFile “必须设置注释与页面中配置的“fileObjName”一致。

/*****************************************
 * 
 *@copyright  隐藏~~啦啦
 *
 *
 *****************************************/
package com.iqb.onigiri.manage.action;
import java.util.UUID;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
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.bind.annotation.ResponseBody;
import org.springframework.web.multipart.commons.CommonsMultipartFile;
import com.iqb.onigiri.manage.base.BaseAction;
import com.iqb.onigiri.manage.base.BaseConfig;
import com.iqb.onigiri.manage.util.SpringBeanUtil;
/**
 * 
 * Description: 
 * @author William
 * @version 1.0
 * 
 * Modification History: 
 * Date         Author      Version     Description 
------------------------------------------------------------------
 * 2017年6月8日    William     1.0        1.0 Version 
 * 
*/
@Controller @RequestMapping("/uploadTestAction") public class UploadTestAction extends BaseAction{ /** * 日志类 */ private static Logger log = LoggerFactory.getLogger(UploadTestAction.class); private BaseConfig baseConfig; //此处是配置类 public UploadTestAction () { baseConfig = SpringBeanUtil.getBean(BaseConfig.class);//构造方法,加载BaseConfig类 } /** * * Description: * @param * @return String * @throws * @Author William * Create Date: 2017年6月8日 */ @ResponseBody @RequestMapping(value="/uploadFile",method=RequestMethod.POST, produces = "text/plain;charset=UTF-8") public String uploadFile(@RequestParam("pic")CommonsMultipartFile pic ,HttpServletRequest request,HttpServletResponse response) throws Exception{ //设置文件保存的本地路径 String filePath=baseConfig.getUploadStaticUrl()+"/static/uploadFiles/"; String fileName = pic.getOriginalFilename();//上传文件的原始名称 //为了避免文件名重复,在文件名前加UUID String uuid = UUID.randomUUID().toString().replace("-",""); String uuidFileName = uuid + fileName; //上传文件的新名称 /** * 实际的文件到服务器的类 */ UploadAction upa = new UploadAction(); upa.sendMultiFile(pic.getInputStream(), filePath +uuidFileName); log.debug("文件名称:{}",filePath+uuidFileName); return filePath+uuidFileName; //此处要返回给前端页面,作为存储使用 } }
上面的代码调用了“UploadAction.java”,这个类的作用就是上传文件到服务器。

6. UploadAction.Java 代码如下:

public void sendMultiFile(InputStream is,String urlStr) throws MalformedURLException {
        URL url = new URL(urlStr);
        try {
            urlconnection = url.openConnection();
            urlconnection.setDoOutput(true);
            urlconnection.setDoInput(true);

            if (urlconnection instanceof HttpURLConnection) {
                try {
                    ((HttpURLConnection) urlconnection).setRequestMethod("PUT");
                    ((HttpURLConnection) urlconnection).setRequestProperty(
                            "Connection", "Keep-Alive");
                    ((HttpURLConnection) urlconnection).setRequestProperty(
                            "Cache-Control", "no-cache");
                    ((HttpURLConnection) urlconnection).setRequestProperty(
                            "Content-type", "text/plain");
                    ((HttpURLConnection) urlconnection).connect();

                } catch (ProtocolException e) {
                    e.printStackTrace();
                }

                BufferedOutputStream out = new BufferedOutputStream(
                        urlconnection.getOutputStream());

                out.flush();
                BufferedInputStream in = new BufferedInputStream(is);

                try {
                    byte[] buffer = new byte[1024];
                    int len = 0;
                    while ((len = in.read(buffer)) > -1)
                        out.write(buffer, 0, len);
                } finally {
                    out.close();
                    in.close();
                }

                try {
//                  System.out.println("here");
                    InputStream inputStream;
                    int responseCode = ((HttpURLConnection) urlconnection)
                            .getResponseCode();
//                  System.out.println("responseCode:"+responseCode);
                    if ((responseCode >= 200) && (responseCode <= 202)) {
//                      System.out.println("成功");
                    } else {
                        inputStream = ((HttpURLConnection) urlconnection)
                                .getErrorStream();
                    }
                    ((HttpURLConnection) urlconnection).disconnect();

                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
        } catch (Exception e) {

        }
    }

以上一系列代码完成,即可成功上传文件,贴图。

成功的图,与flash版本无差别, 此处不贴了。

此贴内容到此为止,如看到此贴的朋友,有建议可随意留言,勿喷,谢谢。

你可能感兴趣的:(前端,技术类)