多图上传功能

作者: 进击的程序源 | 来源:发表于2017-05-03 18:24 被阅读0次

首先介绍一下多图上传有两个好用的框架:
1.uploadify
2.zyupload
我用的是zyupload,因为它的效果在手机端用非常友好,下载地址:http://download.csdn.net/detail/sinat_29662475/9580166

使用步骤如下:
(1)引用

<link rel="stylesheet" href="zyupload/skins/zyupload-1.0.0.min.css " type="text/css">
<script type="text/javascript" src="zyupload/zyupload.basic-1.0.0.min.js"></script>

(2)body里面

<div class="upload_btn" style="display: none;" id="upload"></div>
<div id="zyupload" class="zyupload" style="border: 0px;display:block" ></div>

(3)copy一段script代码

<script type="text/javascript">
            $(function(){
                // 初始化插件
                $("#zyupload").zyUpload({
                    width            :   "100%",                 // 宽度
                    height           :   "100px",                 // 宽度
                    itemWidth        :   "75px",                 // 文件项的宽度
                    itemHeight       :   "75px",                 // 文件项的高度
                    url              :   "http://10.0.21.80:8080/ShanglinApp/servlet/UploadAction",  // 上传文件的路径
                    fileType         :   ["jpg","png","js","exe"],// 上传文件的类型
                    fileSize         :   51200000,                // 上传文件的大小
                    multiple         :   true,                    // 是否可以多个文件上传
                    dragDrop         :   false,                   // 是否可以拖动上传文件
                    tailor           :   false,                   // 是否可以裁剪图片
                    del              :   true,                    // 是否可以删除文件
                    finishDel        :   false,                   // 是否在上传文件完成后删除预览
                    /* 外部获得的回调接口 */
                    onSelect: function(selectFiles, allFiles){    // 选择文件的回调方法  selectFile:当前选中的文件  allFiles:还没上传的全部文件
                        console.info("当前选择了以下文件:");
                        console.info(selectFiles);
                    },
                    onDelete: function(file, files){              // 删除一个文件的回调方法 file:当前删除的文件  files:删除之后的文件
                        console.info("当前删除了此文件:");
                        console.info(file.name);
                    },
                    onSuccess: function(file, response){          // 文件上传成功的回调方法
                        console.info("此文件上传成功:");
                        console.info(file.name);
                        console.info("此文件上传到服务器地址:");
                        console.info(response);
//                      setTimeout(show(),2000);
                        
//                      $("#uploadInf").append("<p>上传成功,文件地址是:" + response + "</p>");
                    },
                    onFailure: function(file, response){          // 文件上传失败的回调方法
                        console.info("此文件上传失败:");
                        console.info(file.name);
                        alert("上传文件失败");
                    },
                    onComplete: function(response){               // 上传完成的回调方法
                        console.info("文件上传完成");
                        console.info(response);
                        setTimeout(show(),2000);
                    }
                });
                
            });
            
            function show(){
                mui.alert("景点评论成功,点击确定关闭","景点评论","确定",function () {
                    document.location.href="tab-webview-subpage-about.html";
                    
                });
            }
        
        </script> 

(4)点击上传的位置对id为upload的这个div调用click事件就ok了

$("#upload").click();

(5)后台代码
demo里面有一个 UploadAction.java文件,做适当修改就可以用了,很方便

package servlet;

import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.io.PrintWriter;
import java.sql.Connection;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.sql.Statement;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.Iterator;
import java.util.List;
import java.util.Random;

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

import org.apache.commons.fileupload.FileItem;
import org.apache.commons.fileupload.FileUploadException;
import org.apache.commons.fileupload.disk.DiskFileItemFactory;
import org.apache.commons.fileupload.servlet.ServletFileUpload;
import org.apache.commons.fileupload.util.Streams;

import utils.JdbcUtils;

/**
 * Servlet implementation class UploadAction
 */
public class UploadAction extends HttpServlet {
    private static final long serialVersionUID = 1L;
    
    //上传文件的保存路径  
    protected String configPath = "upload/widget";  
  
    protected String dirTemp = "upload/widget/temp";  
      
    protected String dirName = "file";  
       
    /**
     * @see HttpServlet#HttpServlet()
     */
    public UploadAction() {
        super();
        // TODO Auto-generated constructor stub
    }

    /**
     * @see HttpServlet#doGet(HttpServletRequest request, HttpServletResponse response)
     */
    protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        // TODO Auto-generated method stub
        doPost(request, response);
        response.setHeader("Access-Control-Allow-Origin", "*");
        response.setCharacterEncoding("UTF-8");
        response.setContentType("text/html");
        System.out.println("get");
    }

    /**
     * @see HttpServlet#doPost(HttpServletRequest request, HttpServletResponse response)
     */
    protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        // TODO Auto-generated method stub
        response.setHeader("Access-Control-Allow-Origin","*");
        response.setCharacterEncoding("UTF-8");
        response.setContentType("text/html");
//      response.setHeader("Access-Control-Allow-Origin", "*");
//        request.setCharacterEncoding("UTF-8");  
//        response.setContentType("text/html; charset=UTF-8");  
        PrintWriter out = response.getWriter();  
          
        //文件保存目录路径  
//        String savePath = "E:/";  
        String savePath = this.getServletContext().getRealPath("/") + configPath;  
        // 临时文件目录   
        String tempPath = this.getServletContext().getRealPath("/") + dirTemp;  
          
        SimpleDateFormat sdf = new SimpleDateFormat("yyyyMM");  
        String ymd = sdf.format(new Date());  
        savePath += "/" + ymd + "/";  
        //创建文件夹  
        File dirFile = new File(savePath);  
        if (!dirFile.exists()) {  
            dirFile.mkdirs();  
        }  
          
        tempPath += "/" + ymd + "/";  
        //创建临时文件夹  
        File dirTempFile = new File(tempPath);  
        if (!dirTempFile.exists()) {  
            dirTempFile.mkdirs();  
        }  
          
        DiskFileItemFactory  factory = new DiskFileItemFactory();  
        factory.setSizeThreshold(20 * 1024 * 1024); //设定使用内存超过5M时,将产生临时文件并存储于临时目录中。     
        factory.setRepository(new File(tempPath)); //设定存储临时文件的目录。     
        ServletFileUpload upload = new ServletFileUpload(factory);  
        upload.setHeaderEncoding("UTF-8");  
        try {  
            List items = upload.parseRequest(request);  
            System.out.println("items = " + items);  
            Iterator itr = items.iterator();  
              
            while (itr.hasNext())   
            {  
                FileItem item = (FileItem) itr.next();  
                String fileName = item.getName();  
                long fileSize = item.getSize();  
                if (!item.isFormField()) {  
                    String fileExt = fileName.substring(fileName.lastIndexOf(".") + 1).toLowerCase();  
                    SimpleDateFormat df = new SimpleDateFormat("yyyyMMddHHmmss");  
                    String newFileName = df.format(new Date()) + "_" + new Random().nextInt(1000) + "." + fileExt;  
                    try{  
                        File uploadedFile = new File(savePath, newFileName);  
                        
                        OutputStream os = new FileOutputStream(uploadedFile);  
                        InputStream is = item.getInputStream();  
                        byte buf[] = new byte[1024];//可以修改 1024 以提高读取速度  
                        int length = 0;    
                        while( (length = is.read(buf)) > 0 ){    
                            os.write(buf, 0, length);    
                        }    
                        //关闭流    
                        os.flush();  
                        os.close();    
                        is.close();    
                        out.print(savePath+"/"+newFileName);  
                        String getPath = configPath+"/" + ymd + "//"+newFileName;
                        System.out.println("我得到的路径为:"+getPath);
                        saveImg(getPath);
                    }catch(Exception e){  
                        e.printStackTrace();  
                    }  
                }else {  
                    String filedName = item.getFieldName();  
                    System.out.println("===============");   
                    System.out.println(new String(item.getString().getBytes("iso-8859-1"),"utf-8"));  
                    System.out.println("FieldName:"+filedName);  
                    // 获得裁剪部分的坐标和宽高
                    System.out.println("String:"+item.getString());  
                }             
            }   
              
        } catch (FileUploadException e) {  
            // TODO Auto-generated catch block  
            e.printStackTrace();  
        }  
        out.flush();  
        out.close(); 
        
    }
    
    public void saveImg(String img) throws Exception{
        String imgs = "";
        Connection conn = JdbcUtils.getConnection();
        Statement stmt = conn.createStatement();
        String sql = "select * from comment order by id desc limit 1";
        ResultSet rs = stmt.executeQuery(sql);
        int id = 0;
        while(rs!=null&&rs.next()){
            id = rs.getInt("id");
            String imgGet = rs.getString("imgs");
            if(imgGet!=null){
                imgs = imgGet+"|"+img;
            }else{
                imgs = img;
            }
        }
        String sql2 = "update comment set imgs = '"+imgs+"' where id = '"+id+"'";
        int executeUpdate = stmt.executeUpdate(sql2);
        JdbcUtils.close(conn, stmt, rs);
    }
}

效果如下:(上传过程中会有进度条,很棒的体验)


image.png image.png

相关文章

网友评论

    本文标题:多图上传功能

    本文链接:https://www.haomeiwen.com/subject/lgkltxtx.html