文件上传

文件上传工具类

import java.io.File;
import java.io.IOException;
import java.nio.file.Files;
import java.nio.file.Path;
import java.nio.file.Paths;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.HashMap;
import java.util.Map;
import java.util.UUID;

import org.springframework.util.ResourceUtils;
import org.springframework.web.multipart.MultipartFile;
import org.springframework.web.servlet.mvc.support.RedirectAttributes;

public class Uploadfileutil {
	
	public Map<String, String> fileUpload(MultipartFile srcFile) {
		
		Map<String, String> resultmap = new HashMap<String,String>();
		
		String oldname;
		String newname;
		String filesize;
		String filetype;
		//前端没有选择文件,srcFile为空
		if(srcFile.isEmpty()) {
			
			resultmap.put("message", "请选择一个文件");
			resultmap.put("code", "false");
		return resultmap;
		}
		//选择了文件,开始上传操作
		try {
		//构建上传目标路径,找到了项目的target的classes目录
		File destFile = new File(ResourceUtils.getURL("E:\\yzj\\1").getPath());
		if(!destFile.exists()) {
		destFile = new File("");
		}
		//输出目标文件的绝对路径
//		System.out.println("file path:"+destFile.getAbsolutePath());
		//拼接子路径
		SimpleDateFormat sf_ = new SimpleDateFormat("yyyyMMddHHmmss");
		String times = sf_.format(new Date());
		File upload = new File(destFile.getAbsolutePath());
		
		String uuid = UUID.randomUUID().toString().replaceAll("-", "");
		// 获得文件原始名称
		String fileName = srcFile.getOriginalFilename();
		// 获得文件后缀名称
		String suffixName = fileName.substring(fileName.lastIndexOf(".") + 1).toLowerCase();
		filetype = suffixName;
		// 生成最新的uuid文件名称
		String newFileName = uuid + "."+ suffixName;
		newname = newFileName;
		//若目标文件夹不存在,则创建
		if(!upload.exists()) {
		upload.mkdirs();
		}
//		System.out.println("完整的上传路径:"+upload.getAbsolutePath()+"/"+srcFile.getOriginalFilename());
		oldname = srcFile.getOriginalFilename();
		//根据srcFile大小,准备一个字节数组
		byte[] bytes = srcFile.getBytes();
		//拼接上传路径
		//Path path = Paths.get(UPLOAD_FOLDER + srcFile.getOriginalFilename());
		//通过项目路径,拼接上传路径
		Path path = Paths.get(upload.getAbsolutePath()+"/"+newFileName);
//		System.out.println(srcFile.getSize()/1024+"KB");
		filesize = srcFile.getSize()/1024+"KB";
//		Path path = Paths.get(upload.getAbsolutePath()+"/"+srcFile.getOriginalFilename());
		//** 开始将源文件写入目标地址
		Files.write(path, bytes);
		
//		System.out.println(newFileName);
		} catch (IOException e) {
		e.printStackTrace();
		resultmap.put("message", "出现异常");
		resultmap.put("code", "false");
		return resultmap;
		}
		resultmap.put("message", "上传成功");
		resultmap.put("code", "true");
		
		resultmap.put("file_oldname", oldname);
		resultmap.put("file_newname", newname);
		resultmap.put("file_size", filesize);
		resultmap.put("file_type", filetype);
		return resultmap;
		}
	
	

}

前端代码

 

<div class="demo">
  <div id="uploadfile">
       <!--用来存放文件信息-->
             <div id="thelist" class="uploader-list"></div>
             <div class="form-group form-inline">
             <div id="picker" style="float:left">选择文件</div> &nbsp;
             <button id="ctlBtn" class="btn btn-default" style="padding:8px 15px;">开始上传</button>
               </div>
         </div>
   </div>




<style>
.demo{min-width:360px;margin:30px auto;padding:10px 20px}
.demo h3{line-height:40px; font-weight: bold;}
.file-item{float: left; position: relative; width: 110px;height: 110px; margin: 0 20px 20px 0; padding: 4px;}
.file-item .info{overflow: hidden;}
.uploader-list{width: 100%; overflow: hidden;}
</style>




<script>
$(function(){
	var $list = $('#thelist'),
        $btn = $('#ctlBtn');
	
	var listid = $("#idstr").val();
 
    var uploader = WebUploader.create({
      resize: false, // 不压缩image     
      swf: 'js/uploader.swf', // swf文件路径
      server: 'upload?listid='+listid, // 文件接收服务端。
      pick: '#picker', // 选择文件的按钮。可选
      chunked: true, //是否要分片处理大文件上传
      chunkSize:10*1024*1024, //分片上传,每片2M,默认是5M
      //auto: false //选择文件后是否自动上传
      //chunkRetry : 2, //如果某个分片由于网络问题出错,允许自动重传次数
      //runtimeOrder: 'html5,flash',
       accept: {
         title: 'Images',
         extensions: 'pdf',
         mimeTypes: '*'
       }
    });
    // 当有文件被添加进队列的时候
    uploader.on( 'fileQueued', function( file ) {
        $list.append( '<div id="' + file.id + '" class="item">' +
            '<h4 class="info">' + file.name + '</h4>' +
            '<p class="state">等待上传...</p>' +
        '</div>' );
    });
    // 文件上传过程中创建进度条实时显示。
    uploader.on( 'uploadProgress', function( file, percentage ) {
        var $li = $( '#'+file.id ),
            $percent = $li.find('.progress .progress-bar');

        // 避免重复创建
        if ( !$percent.length ) {
            $percent = $('<div class="progress progress-striped active">' +
              '<div class="progress-bar" role="progressbar" style="width: 0%">' +
              '</div>' +
            '</div>').appendTo( $li ).find('.progress-bar');
        }

        $li.find('p.state').text('上传中');

        $percent.css( 'width', percentage * 100 + '%' );
    });
    // 文件上传成功
    uploader.on( 'uploadSuccess', function( file , res ) {
        //console.log(res.filePath);
        // console.log(res.code);
        if(res.code == 'true'){
        	$( '#'+file.id ).find('p.state').text('已上传');
        	window.parent.ZxManualXzxkxx02.table.refresh();
            ZxManualXzxkxx02InfoDlg.close();
        }else {
        	$( '#'+file.id ).find('p.state').text('上传失败请刷新页面再试');
        }
        
    });

    // 文件上传失败,显示上传出错
    uploader.on( 'uploadError', function( file, res ) {
        // console.log(res.code);
    	$( '#'+file.id ).find('p.state').text('上传失败!服务器异常请,联系管理员');
    });
    // 完成上传完
    uploader.on( 'uploadComplete', function( file ) {
        $( '#'+file.id ).find('.progress').fadeOut();
    });

    $btn.on('click', function () {
            if ($(this).hasClass('disabled')) {
                return false;
            }
            uploader.upload();
        });

});

//上传图片
 // 初始化Web Uploader
var uploader = WebUploader.create({

    // 选完文件后,是否自动上传。
    auto: true,

    // swf文件路径
    swf: 'js/Uploader.swf',

    // 文件接收服务端。
    server: 'upload.php',

    // 选择文件的按钮。可选。
    // 内部根据当前运行是创建,可能是input元素,也可能是flash.
    pick: '#imgPicker',

    // 只允许选择图片文件。
    accept: {
        title: 'Images',
        extensions: 'gif,jpg,jpeg,bmp,png',
        mimeTypes: 'image/*'
    }
});

// 当有文件添加进来的时候
uploader.on( 'fileQueued', function( file ) {
    var $list = $("#fileList"),
        $li = $(
            '<div id="' + file.id + '" class="file-item thumbnail">' +
                '<img>' +
                '<div class="info">' + file.name + '</div>' +
            '</div>'
            ),
        $img = $li.find('img');


    // $list为容器jQuery实例
    $list.append( $li );

    // 创建缩略图
    // 如果为非图片文件,可以不用调用此方法。
    // thumbnailWidth x thumbnailHeight 为 100 x 100
    uploader.makeThumb( file, function( error, src ) {
        if ( error ) {
            $img.replaceWith('<span>不能预览</span>');
            return;
        }

        $img.attr( 'src', src );
    }, 100, 100 );
});
// 文件上传过程中创建进度条实时显示。
uploader.on( 'uploadProgress', function( file, percentage ) {
    var $li = $( '#'+file.id ),
        $percent = $li.find('.progress span');

    // 避免重复创建
    if ( !$percent.length ) {
        $percent = $('<p class="progress"><span></span></p>')
                .appendTo( $li )
                .find('span');
    }

    $percent.css( 'width', percentage * 100 + '%' );
});

// 文件上传成功,给item添加成功class, 用样式标记上传成功。
uploader.on( 'uploadSuccess', function( file ) {
    $( '#'+file.id ).addClass('upload-state-done');
});

// 文件上传失败,显示上传出错。
uploader.on( 'uploadError', function( file ) {
    var $li = $( '#'+file.id ),
        $error = $li.find('div.error');

    // 避免重复创建
    if ( !$error.length ) {
        $error = $('<div class="error"></div>').appendTo( $li );
    }

    $error.text('上传失败');
});

// 完成上传完了,成功或者失败,先删除进度条。
uploader.on( 'uploadComplete', function( file ) {
    $( '#'+file.id ).find('.progress').remove();
});

</script>

 

 

 

 

 

 

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 打赏
    打赏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

yzzzjj

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值