当前位置: 移动技术网 > IT编程>开发语言>.net > swfupload文件上传组件 服务端用servlet配置教程

swfupload文件上传组件 服务端用servlet配置教程

2018年04月19日  | 移动技术网IT编程  | 我要评论

445544,便携切割机,宇文家族

swfupload是个不错的上传组件,可以实现无刷新上传图片,并返回自己想要的数据,今天写了一个用java servlet来作为服务端接收客户端文件,自己在项目中也有使用,功能是实现远程上传文件并返回上传后在服务端的文件路径。

1,在官网下载swfupload,地址:https://demo.swfupload.org,

2,编写上传页面(这里的上传页面完全是从官网整过来的),并在下载的文件中找到以下html代码中的js文件并并入,(我下载的包中没有default.css文件,以下css也是我是官网copy过来的,里面用到一个按钮的样式,包括图片,如果不想自己写也可以先整过来),部分详情看页面注释的几个函数。

[html]  

<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "https://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">  

<html>  

<head>  

<meta http-equiv="Content-Type" content="text/html; charset=utf-8" />  

<title>上传图片</title>  

<jsp:include page="/home/head_html.jsp" flush="true" />  

<script type="text/javascript" src="/myimg/copy.js"></script>  

<link href="upload/default.css" rel="stylesheet" type="text/css" />  

<script type="text/javascript" src="upload/swfupload.js"></script>  

<script type="text/javascript" src="upload/swfupload.swfobject.js"></script>  

<script type="text/javascript" src="upload/fileprogress.js"></script>  

<script type="text/javascript" src="upload/handers.js"></script>  

<script type="text/javascript">  

        var swfu;  

  

        window.onload = function () {  

            swfu = new SWFUpload({  

                // Backend settings    

                upload_url: "<%=basePath%>/upload/uploadImg",//服务端接收的servlet地址  

                file_post_name: "resume_file",  

  

                // Flash file settings  

                file_size_limit : "10 MB",  

                file_types : "*.*",         // or you could use something like: "*.doc;*.wpd;*.pdf",  

                file_types_description : "All Files",  

                file_upload_limit : "0",  

                              // 向服务端传递的参数 user代表上传的用户,p我是用来代表某个产品类别的意思,作为上传文件的路径用,具体的看自己需求  

                         post_params: {  

                    "user" : "admin",  

                    "p" : "x"  

                },  

                file_queue_limit : "1",  

                use_query_string : true,  

                // Event handler settings  

                swfupload_loaded_handler : swfUploadLoaded,  

                  

                file_dialog_start_handler: fileDialogStart,  

                file_queued_handler : fileQueued,  

                file_queue_error_handler : fileQueueError,  

                file_dialog_complete_handler : fileDialogComplete,//当你选择文件后执行的函数,你可以在这个函数里设置成选择文件后直接上传或者提交表单时再上传  

                  

                //upload_start_handler : uploadStart,   // I could do some client/JavaScript validation here, but I don't need to.  

                upload_progress_handler : uploadProgress,  

                upload_error_handler : uploadError,  

                upload_success_handler : uploadSuccess,//文件上传成功后执行的函数,服务端返回的数据也是从这里获取,详情在handlers.js中  

                upload_complete_handler : uploadComplete,//文件上传完成后的操作  

  

                // Button Settings  

                button_image_url : "images/XPButtonUploadText_61x22.png",  

                button_placeholder_id : "spanButtonPlaceholder",  

                button_width: 61,  

                button_height: 22,  

                  

                // Flash Settings  

                flash_url : "upload/Flash/swfupload.swf",  

  

                custom_settings : {  

                    progress_target : "fsUploadProgress",  

                    //upload_successful : false  

                },  

                  

                // Debug settings  

                debug: false  

            });  

  

        };  

    </script>  

</head>  

<body>  

<p id="header">  

    <h1 id="logo"><a href="../">SWFUpload</a></h1>  

    <p id="version">v2.2.0</p>  

</p>  

  

<p id="content">  

  

    <h2>Classic Form Demo</h2>  

    <form id="form1" action="thanks.php" enctype="multipart/form-data" method="post">  

        <p>This demo shows how SWFUpload might be combined with an HTML form.  It also demonstrates graceful degradation (using the graceful degradation plugin).  

            This demo also demonstrates the use of the server_data parameter.  This demo requires Flash Player 9+</p>  

        <p class="fieldset">  

            <span class="legend">Submit your Application</span>  

            <table style="vertical-align:top;">  

                <tr>  

                    <td><label for="lastname">Last Name:</label></td>  

                    <td><input name="lastname" id="lastname" type="text" style="width: 200px" /></td>  

                </tr>  

                <tr>  

                    <td><label for="firstname">First Name:</label></td>  

                    <td><input name="firstname" id="firstname" type="text" style="width: 200px" /></td>  

                </tr>  

                <tr>  

                    <td><label for="education">Education:</label></td>  

                    <td><textarea name="education"  id="education" cols="0" rows="0" style="width: 400px; height: 100px;"></textarea></td>  

                </tr>  

                <tr>  

                    <td><label for="txtFileName">Resume:</label></td>  

                    <td>  

                        <p>  

                            <p>  

                                <input type="text" id="txtFileName" disabled="true" style="border: solid 1px; background-color: #FFFFFF;" />  

                                <span id="spanButtonPlaceholder"></span>  

                                (10 MB max)  

                            </p>  

                            <p class="flash" id="fsUploadProgress">  

                                <!-- This is where the file progress gets shown.  SWFUpload doesn't update the UI directly.  

                                            The Handlers (in handlers.js) process the upload events and make the UI updates -->  

                            </p>  

                            <input type="hidden" name="hidFileID" id="hidFileID" value="" />  

                            <!-- This is where the file ID is stored after SWFUpload uploads the file and gets the ID back from upload.php -->  

                        </p>  

                    </td>  

                </tr>  

                <tr>  

                    <td><label for="references">References:</label></td>  

                    <td><textarea name="references" id="references" cols="0" rows="0" style="width: 400px; height: 100px;"></textarea></td>  

                </tr>  

            </table>  

            <br />  

            <input type="submit" value="Submit Application" id="btnSubmit" />  

        </p>  

    </form>  

</p>  

</body>  

</html>  

3,编写并配置servlet,servlet大部分是网上一朋友写的,我只是按自己的需求修改了一下

[java]  

public class UploadImg extends HttpServlet {  

  

    private static final long serialVersionUID = 1L;  

      

    @Override  

    protected void doGet(HttpServletRequest req, HttpServletResponse resp)  

            throws ServletException, IOException {  

        doPost(req, resp);  

    }  

    @Override  

    protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {  

          

        System.out.println("upload file begin");  

        //接收参数  

                StringBuffer path=new StringBuffer("/uploadfiles/");  

                String user = request.getParameter("user");  

                String product = request.getParameter("p");  

                if(null == user){  

                    System.out.println("用户为空");  

                    return;  

                }  

                if(null == product){  

                    System.out.println("产品为空");  

                    return;  

                }  

                if(product.equals("x")){  

                    path.append("xiaoxuntong/"+user);  

                }else{  

                    System.out.println("当前没有该产品");  

                    return;  

                }  

                String realpath = request.getSession().getServletContext().getRealPath(path.toString());  

                System.out.println("_________path:"+realpath);  

              

                List<FileEntity> fileList;  

                fileList = (List)request.getAttribute("fileList");  

                if(fileList==null)  

                    fileList = new ArrayList<FileEntity>();  

                  

                //接收上传文件  

                String uploadSign = request.getParameter("upload");  

                    

                  uploadSign = "1";  

                  //上传操作  

                  if(null != uploadSign && !"".equals(uploadSign)){  

                      FileItemFactory factory = new DiskFileItemFactory();  

                      ServletFileUpload upload = new ServletFileUpload(factory);  

                      //upload.setHeaderEncoding("UTF-8");  

                      try{  

                          List items = upload.parseRequest(request);  

                          if(null != items){  

                              Iterator itr = items.iterator();  

                              int i = 0;  

                              while(itr.hasNext()){  

                                  FileItem item = (FileItem)itr.next();  

                                  FileEntity file = new FileEntity();//  

                                  if(item.isFormField()){  

                                      continue;  

                                  }else{  

                                      //可修改上传后的文件命名格式  

                                      SimpleDateFormat sdf=new SimpleDateFormat("yyyyMMddkkmmss");//以当前精确到秒的日期为上传的文件的文件名  

                                      SimpleDateFormat sdd=new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");  

                                      String type = item.getName().split("\\.")[1];//获取文件类型  

                                        

                                      System.out.println("文件名称:"+item.getName());  

                                      System.out.println("从GBK转到UTF-8输出:"+new String(item.getName().getBytes("GBK"),"UTF-8"));  

                                      String fileName=sdf.format(new Date())+"."+type;  

                                      File savedFile = new File(realpath,fileName);  

                                      File luFile = new File(realpath);  

                                      if(!luFile.exists())luFile.mkdirs();  

                                      //把文件放到列表中,在前台显示  

                                      System.out.println("服务器上对应的文件名称:"+sdf.format(new Date())+"."+type);  

                                      System.out.println("完整路径:"+realpath+"/"+sdf.format(new Date())+"."+type);  

                                      file.setId(sdf.format(new Date()));  

                                      file.setDate(sdd.format(new Date()));  

                                      file.setFilename(fileName);  

                                      file.setFilepath(realpath+"/"+sdf.format(new Date())+"."+type);  

                                      file.setFilesize(item.getSize()+"");  

                                      file.setFiletype(type);  

                                      file.setMark("0");  

                                      fileList.add(file);  

                                        

                                      item.write(savedFile);  

                                  }  

                              }  

                          }  

                      }catch(Exception e){  

                          e.printStackTrace();  

                      }  

                  }  

                  

                  

                response.setContentType("text/html");  

                response.setCharacterEncoding("UTF-8");  

                PrintWriter out = response.getWriter();  

                if(fileList!=null){  

                    for(int i=0;i<fileList.size();i++){  

                        FileEntity file = (FileEntity)fileList.get(i);  

                                                 //输出文件的绝对路径  

                                               out.println(request.getScheme()+"://"+request.getServerName()+":"+request.getServerPort()+"/"+request.getContextPath()+path.toString()+"/"+file.getFilename());  

                    }  

                }  

    }  

如对本文有疑问,请在下面进行留言讨论,广大热心网友会与你互动!! 点击进行留言回复

相关文章:

验证码:
移动技术网