uploadify前台上传文件,java后台处理的例子

1、先创建一个简单的web项目upload (如图1-1)

2、插件的准备

(1)、去uploadify的官网下载一个uploadify插件,然后解压新建个js文件夹放进去(这个不强求,只要路径对了就可以)

(2)、准备所需要的后端处理上传文件的jar包:commons-fileupload-1.2.1.jar

3、新建一个JSP即index.jsp +servlet即UploadServlet.java

图1-1

4、花几分钟对这些简单的配置完成后就可以看看index.jsp与UoloadServlet.java

(1)index.jsp

<%@ page language="java" import="java.util.*" pageEncoding="UTF-8"%>
<%
String path = request.getContextPath();
String basePath = request.getScheme()+"://"+request.getServerName()+":"+request.getServerPort()+path+"/";
%>

<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN">
<html>
	<head>
		<base href="<%=basePath%>">
		<title>My JSP ‘index.jsp‘ starting page</title>
		<meta http-equiv="pragma" content="no-cache">
		<meta http-equiv="cache-control" content="no-cache">
		<meta http-equiv="expires" content="0">
		<meta http-equiv="keywords" content="keyword1,keyword2,keyword3">
		<meta http-equiv="description" content="This is my page">
		<meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
		<link rel="stylesheet" type="text/css" href="css/uploadify.css">
		<script src="<%=basePath%>js/uploadify/jquery-1.4.2.min.js"></script>
		<script src="<%=basePath%>js/uploadify/jquery.uploadify.v2.1.4.min.js"></script>
		<script src="<%=basePath%>js/uploadify/swfobject.js"></script>
	</head>
	<body>
		This is my JSP page.
		<br>
		<table class="stable tp0" cellSpacing="0" cellPadding="0" border="0">
            <tr>
                <td width="15%" align="left" colspan="4" style="padding-left: 158px">

                    <input type="hidden" id="fileSize" value="0" />

                    <div id="custom-queue"></div> 附件:<input id="uploadify" type="file"
                    name="Filedata" />
                </td>
            </tr>
        </table>
	</body>
	<script type="text/javascript">
  $(document).ready(function(){

      $(document).ready(function () {
            $("#uploadify").uploadify({
                ‘uploader‘: ‘<%=basePath%>js/uploadify/uploadify.swf‘,
                ‘script‘: ‘<%=basePath%>servlet/UploadServlet‘,
                ‘cancelImg‘: ‘<%=basePath%>js/uploadify/cancel.png‘,
                ‘folder‘: ‘upload‘,
                ‘queueID‘ : ‘custom-queue‘,
                ‘auto‘:true,
                ‘multi‘:true,
                ‘fileDataName‘:‘Filedata‘,
                 ‘onCancel‘ : function(file) {
                },
                ‘onUploadError‘ : function(file, errorCode, errorMsg, errorString) {
                    alert(456);
                }
            });
        });
  });

  </script>
</html>

(2).UoloadServlet.java

package coms;

import java.io.File;
import java.io.IOException;
import java.util.Iterator;
import java.util.List;
import java.util.UUID;

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;

public class UploadServlet extends HttpServlet {

    @Override
    protected void doPost(HttpServletRequest request,
            HttpServletResponse response) throws ServletException, IOException {
        String savePath = this.getServletConfig().getServletContext()
                .getRealPath("");
        //保存文件的路径
        savePath = savePath + "/upload/";
        File f1 = new File(savePath);
        System.out.println(savePath);
        //如果文件不存在,就新建一个
        if (!f1.exists()) {
            f1.mkdirs();
        }
        //这个是文件上传需要的类,具体去百度看看,现在只管使用就好
        DiskFileItemFactory fac = new DiskFileItemFactory();
        ServletFileUpload upload = new ServletFileUpload(fac);
        upload.setHeaderEncoding("utf-8");
        List fileList = null;
        try {
            fileList = upload.parseRequest(request);
        } catch (FileUploadException ex) {
            return;
        }
        //迭代器,搜索前端发送过来的文件
        Iterator<FileItem> it = fileList.iterator();
        String name = "";
        String extName = "";
        while (it.hasNext()) {
            FileItem item = it.next();
            //判断该表单项是否是普通类型
            if (!item.isFormField()) {
                name = item.getName();
                long size = item.getSize();
                String type = item.getContentType();
                System.out.println(size + " " + type);
                if (name == null || name.trim().equals("")) {
                    continue;
                }
                // 扩展名格式: extName就是文件的后缀,例如 .txt
                if (name.lastIndexOf(".") >= 0) {
                    extName = name.substring(name.lastIndexOf("."));
                }
                File file = null;
                do {
                    // 生成文件名:
                    name = UUID.randomUUID().toString();
                    file = new File(savePath + name + extName);
                } while (file.exists());
                File saveFile = new File(savePath + name + extName);
                try {
                    item.write(saveFile);
                } catch (Exception e) {
                    e.printStackTrace();
                }
            }
        }
        response.getWriter().print(name + extName);
    }

}

对于jsp与java没有好好说明,如果不懂可以私聊我,其实花了很多个小时才使用这个uploadify,主要是因为以为上传只要uploadify插件就可以,原来还需要:commons-fileupload-1.2.1.jar ,我是一个喜欢分享的人,希望每个人有能力都能写写博客,让更多人好好学习

时间: 2024-10-27 11:39:55

uploadify前台上传文件,java后台处理的例子的相关文章

uploadify+批量上传文件+java

<%@ page language="java" contentType="text/html; charset=UTF-8" pageEncoding="UTF-8"%> <% String path = request.getContextPath(); String basePath = request.getScheme()+"://"+request.getServerName()+":&

asp.net中使用uploadify插件上传文件, session中的值丢失的问题

工作中遇到使用uploadify插件上传文件后,后台代码中的session[XXX]值为null的问题,反复跟踪,发现不是值丢失,而是sessionID发生了变化,而引起SessionID发生变化的原因就是因为使用了uplodify插件 解决方法: <script type="text/javascript"> var auth = "<% = Request.Cookies[FormsAuthentication.FormsCookieName]==nul

多文件上传以及java后台接受

最近项目用到的,实现多文件以及一些信息上传, 以及后台接收及读取用到了spring及springmvc相关框架. 不多说废话,直接上例子(这有关键代码) 首先,前台页面 <form action="/uploader/upload/uploadFiles" method="post" enctype="multipart/form-data"> <input type="file"size="30&

完整uploadify批量上传文件插件使用

1.首先准备uploadify的js文件,网上一搜一大堆 2.上传页面UpFilePage.aspx 关键代码: <html xmlns="http://www.w3.org/1999/xhtml"><head runat="server"><meta http-equiv="Content-Type" content="text/html; charset=utf-8"/> <tit

使用uploadify组件上传文件

uploadify是和jQuery结合使用的异步上传组件,主要功能是批量上传文件,使用多线程来上传多个组件. 下载并导入js和样式文件 在正式学习uploadify组件之前,首先就是去官网下载最新的js和css等. http://www.uploadify.com/download/ 解压后如图:上面使用红色标示的文件是需要引入到项目中的.另外别忘了引入jquery.js文件 html页面以及上传条件的编写 <html> <head> <base href="<

struts利用插件jqueryupload上传文件,后台处理文件代码

package cn.axhu.education.action.file; import cn.axhu.education.common.FileSystemConfig;import cn.axhu.education.common.utils.FileUtils;import net.ruixin.web.struts2.SimpleActionSupport;import org.apache.struts2.convention.annotation.Action;import or

springmvc利用jqueryupload上传文件,后台处理方法

public void importIdentifySchemeFile(Integer id,Integer type,HttpServletRequest request, HttpServletResponse response){ PrintWriter out = null;          try {              //初始化变量              InputStream stream = null;              String ret_fileNa

sae 上传文件 java实现

不讲废话上代码 1 /** 2 * 上传语音消息至sae服务器 3 * 4 * @param requestUrl 上传链接 5 * @param requestMethod http请求方式 6 */ 7 8 public static boolean httpRequestUploadVoice(String requestUrl, String requestMethod, String fileName){ 9 int byteread = 0; 10 boolean isUpload

Html上传文件,后台接收

html代码:我是发送请求到teacher_center.aspx,不是到.ashx一般处理程序里,需要加 runat="server",有空我再试试发送请求到 .ashx 里 <input type="file" class="upload" id="fu_book_img" name="fu_book_img" runat="server" onchange="Sel