Springmvc+uploadify realizes file upload


          Springmvc+uploadify realizes file upload

 

   I have read a lot of posts about file uploading on the Internet, and there are different opinions. I feel a little messy. Recently, the company's project uses JQuery 's uploadify control for file uploading, so I sorted out the clues and made a document for sharing.

     

   The main advantage of the Uploadify control is that it can realize batch file upload, and provides multiple event listener functions such as onSelect (selected files), onUploadSuccess (upload success callback function), etc., which can control the entire upload process.

 

   After a brief understanding of uploadify , let 's start ...

 

( Because the ssm framework is used in this project, the background processing of springmvc is used as an example ) .

 

 

1. Import uploadify in the project

 

1. First, download the uploadify package file

 

Uploadify official website: http://www.uploadify.com/

 

2. Unzip the package file and get the following structure:

 

 
 

background.jpg    is the background image of the upload box

jquery.uploadify.min.js    mini version uploadify js file, the main function depends on it

jquery-1.9.1.js    understands, there is no requirement for the version

uploadify.css     The beautification file of the upload component

Dynamic effects, progress bar, etc. when uploadify.swf     is uploaded

Uploadify-cancel.png    Cancel upload button image

 

 

 

3. Put the uplodify folder under the webapp



 
 

 

4. Import the necessary jar package

 

commons-fileupload-1.3.1.jar  

commons-io-2.2.jar

 

When using maven , add the following dependencies to pom.xml :

 

<dependency>
			<groupId>commons-fileupload</groupId>
			<artifactId>commons-fileupload</artifactId>
			<version>1.3.1</version>
</dependency>

 

 

 

5、springmvc.xml文件中加入multipart 的解析器

 

 

<bean

id="multipartResolver"  class="org.springframework.web.multipart.commons.CommonsMultipartResolver">

<property name="maxUploadSize" value="1024000"></property>

<property name="defaultEncoding" value="utf-8"/><!--属性:编码-->

</bean>

 

 

注:这个必须配置,一会在controller里抓取上传文件时要用。否则会报错。

 

 

 

 

二、在需要做上传的页面中配置

 

6、在页头导入

 

 

 

7、在页面中需要上传附件的位置插入

 

<div id="uploadfileQueue"></div> //存放选择文件的 图片按钮的 Div

<input type="file" id="file_upload">

<input type="button" value="上传"
 onclick="javascript:$('#file_upload').uplodify('upload','*')" >

<input type="button" value="取消上传"
 onclick="javascript:$('#file_upload').uplodify('cancel','*')" >

    (固定写法)

 

 

 

8js中设置

 

<script type="text/javascript">

$(document).ready(function() {

    $("#file_upload").uploadify({

        //是否自动上传 true or false
        'auto':false,

        //超时时间上传成功后,将等待服务器的响应时间。
        //在此时间后,若服务器未响应,则默认为成功(因为已经上传,等待服务器的响应) 单位:秒
        'successTimeout':99999,

        //附带值 JSON对象数据,将与每个文件一起发送至服务器端。
        //如果为动态值,请在onUploadStart()中使用settings()方法更改该JSON值
       'formData':{       //可以不写
    	   'user.username':'',
    	   'user.age':''
    	   },  
    	    'onUploadStart': function(file) { 
    	    	var name=$('#username').val();
    	    	var age=$('#age').val();
    	    	$("#file_upload").uploadify(
    	    	"settings", 
    	    	"formData", 
    	    	{'user.username':name,'user.age':age});
    	    	}, 
        //flash
        'swf': "${pageContext.request.contextPath}/uplodify/uploadify.swf",

         //文件选择后的容器div的id值 
        'queueID':'uploadfileQueue',

         //将要上传的文件对象的名称 必须与后台controller中抓取的文件名保持一致    
        'fileObjName':'pic',

        //上传地址
       'uploader':'${pageContext.request.contextPath}/upload/uploadFile',

        //浏览将要上传文件按钮的背景图片路径
        'buttonImage':'${pageContext.request.contextPath}/uplodify/background.jpg',

        //浏览按钮的宽度
        'width':'100',

        //浏览按钮的高度
        'height':'32',

        //在浏览窗口底部的文件类型下拉菜单中显示的文本
        'fileTypeDesc':'支持的格式:',

        //允许上传的文件后缀
        'fileTypeExts':'*.jpg;*.jpge;*.gif;*.png', //有哪些??

        /*上传文件的大小限制允许上传文件的最大 大小。 这个值可以是一个数字或字 符串。
          如果它是一个字符串,它接受一个单位(B, KB, MB, or GB)。
          默认单位为KB您可以将此值设置为0 ,没有限制, 
          单个文件不允许超过所设置的值 如果超过 onSelectError时间被触发*/
        'fileSizeLimit':'100KB',

        //允许上传的文件的最大数量。当达到或超过这个数字,onSelectError事件被触发。
        'queueSizeLimit' : 3,

        //选择上传文件后调用
        'onSelect' : function(file) {
              //alert("123");    
        },

        //返回一个错误,选择文件的时候触发
        'onSelectError':function(file, errorCode, errorMsg){
            switch(errorCode) {
                case -100:
                    alert("上传的文件数量已经超出系统限制的"
                     +$('#file_upload').uploadify('settings','queueSizeLimit')+"个文件!");
                    break;

                case -110:
                    alert("文件 ["+file.name+"] 大小超出系统限制的"
                     +$('#file_upload').uploadify('settings','fileSizeLimit')+"大小!");
                    break;

                case -120:
                    alert("文件 ["+file.name+"] 大小异常!");
                    break;

                case -130:
                    alert("文件 ["+file.name+"] 类型不正确!");
                    break;
            }
        },

        //上传到服务器,服务器返回相应信息到data里
        'onUploadSuccess':function(file, data, response){
            alert("上传成功");
        },

      //当单个文件上传出错时触发
        'onUploadError': function (file, errorCode, errorMsg, errorString) { 
        	alert("上传失败");
        	} 
    });

});

</script>

 

 

 

9、controller中,实现上传

 

//接收上传文件

@RequestMapping(value="uploadFile",method=RequestMethod.POST,produces="text/html;charset=utf-8")

@ResponseBody

public String uploadFile(@RequestParam("pic")CommonsMultipartFile pic,HttpServletRequest req,HttpServletResponse response) throws IOException{

//设置文件保存的本地路径

String filePath = req.getSession().getServletContext().getRealPath("/uploadFiles/");

String fileName = pic.getOriginalFilename();

String fileType = fileName.split("[.]")[1];

//为了避免文件名重复,在文件名前加UUID

String uuid = UUID.randomUUID().toString().replace("-","");

String uuidFileName = uuid + fileName;

File f = new File(filePath+"/"+uuid+"."+fileType);

//将文件保存到服务器

FileUtil.upFile(pic.getInputStream(), uuidFileName, filePath);

return uuidFileName;

}

 

 

 

 

 

这个过程中要用到FileUtil工具类:

 

package com.baidu.util;

 

import java.io.BufferedInputStream;

import java.io.BufferedOutputStream;

import java.io.File;

import java.io.FileInputStream;

import java.io.FileOutputStream;

import java.io.IOException;

import java.io.InputStream;

import java.io.OutputStream;

import java.util.List;

import java.util.zip.ZipEntry;

import java.util.zip.ZipOutputStream;

 

import javax.servlet.http.HttpServletRequest;

import javax.servlet.http.HttpServletResponse;

 

public class FileUtil {

/**

 * 单个文件上传

 * @param is

 * @param fileName

 * @param filePath

 */

public static void upFile(InputStream is,String fileName,String filePath){

FileOutputStream fos = null;

BufferedOutputStream bos = null;

BufferedInputStream bis = null;

File file = new File(filePath);

if(!file.exists()){

file.mkdirs();

}

File f = new File(filePath+"/"+fileName);

try {

bis = new BufferedInputStream(is);

fos = new FileOutputStream(f);

bos = new BufferedOutputStream(fos);

byte[] bt = new byte[4096];

int len;

while((len = bis.read(bt))>0){

bos.write(bt, 0, len);

}

} catch (Exception e) {

e.printStackTrace();

}finally {

try {

if(null != bos){

bos.close();

bos = null;}

if(null != fos){

fos.close();

fos= null;

}

if(null != is){

is.close();

is=null;

}

if (null != bis) {

bis.close();

bis = null;

}

} catch (Exception e) {

e.printStackTrace();

}

}

}

}

 

 

 

 

10、效果图



 
 

 



 
 

 

 

 

三、总结

 

1、多文件的上传其实是多次调用单文件上传的方法,我们看到的批量上传其实是分步执行的,上传一次调用一次单文件上传的方法,不要被假象迷惑。

2、上传成功后可以返回文件的信息,在onUploadSuccess函数中可以获取到,这样就可以在页面上设置一个隐藏域存放返回来的值,比如说文件的id,多文件的话可以在隐藏域中抓取数组。然后随表单提交,更新表数据,这样就能方便的把上传文件的信息添加到数据库表中。

 

 

 

希望对大家有所帮助。

 (转载请注明出处)

 

 

 

Guess you like

Origin http://10.200.1.11:23101/article/api/json?id=326727080&siteId=291194637