批量上传文件,技术环境Java,JS,jsp,SSM

1、jsp页面

<form enctype="multipart/form-data">
    <div class="form-group">
        <input id="uploadfile" type="file" name="file" multiple data-overwrite-initial="false" data-min-file-count="1">
    </div>
</form>

<script>
  $(document).ready(function() {
  	var filePanel = parent.document.getElementById("trainPlanFilePanel");
  	var fileDatagrid = parent.document.getElementById("trainPlanFileTable");
  	var mainId = parent.document.getElementById("mainId");
  	var projectId = $(mainId).val();
  	$("#uploadfile").fileinput({
          language: 'zh', //设置语言
          uploadUrl: '${pageContext.request.contextPath}/loadingSafetyProject/insertProjectFile.htm?loadingSafetyProjectId='+projectId, //上传的地址
          allowedFileExtensions: ['JPG','JPEG','PNG','jpg','jpeg','png','pdf','PDF'],//接收的文件后缀
          overwriteInitial: false,
          showBrowse : true,
          uploadExtraData:{},
          uploadAsync: false, //默认异步上传
          showUpload: true, //是否显示上传按钮
          showRemove : true, //显示移除按钮
          dropZoneEnabled: true,//是否显示拖拽区域
          layoutTemplates:{
          	/* actionDetele: */
          	actionUpload:''
          },
         	showPreview : true, //是否显示预览
          showCaption: true,//是否显示标题
          allowedPreviewTypes: [/* 'image' */''],
          browseClass: "btn btn-primary", //按钮样式     
          minImageWidth: 10, //图片的最小宽度
          minImageHeight: 10,//图片的最小高度
          maxImageWidth: 10,//图片的最大宽度
          maxImageHeight: 10,//图片的最大高度
          maxFileSize: 20480,//单位为kb,如果为0表示不限制文件大小
          minFileCount: 1,
          maxFileCount: 10, //表示允许同时上传的最大文件个数
          enctype: 'multipart/form-data',
         	validateInitialCount:true,
          msgFilesTooMany: "选择上传的文件数量({n}) 超过允许的最大数值{m}!", 
      });
//异步上传返回结果处理
$('#uploadfile').on('fileerror', function(event, data, msg) {
	
});
//异步上传返回结果处理
$("#uploadfile").on("fileuploaded", function (event, data, previewId, index) {
	if(data.response.status == 500){
		parent.disError(data.response.msg);			
	}else if(data.response.status == 200 && data.response.data != ''){
			var projectId = data.response.data;
			parent.relaodCurrentPage(projectId);
	}
      });

//同步上传错误处理
  	$('#uploadfile').on('filebatchuploaderror', function(event, data, msg) {
       
   	});
//同步上传返回结果处理
$("#uploadfile").on("filebatchuploadsuccess", function (event, data, previewId, index) {
	if(data.response.status == 500){
		parent.disError(data.response.msg);			
	}else if(data.response.status == 200 && data.response.data != ''){
			var projectId = data.response.data;
			parent.relaodCurrentPage(projectId);
	}
});
//上传前
$('#uploadfile').on('filepreupload', function(event, data, previewId, index) {
    var form = data.form, files = data.files, extra = data.extra,
    response = data.response, reader = data.reader;
}); 


});
</script>

2、后台控制器controller

@RequestMapping(value="/insertProjectFile",method=RequestMethod.POST,produces="text/html;charset=utf-8")
	public void insertProjectFile(@RequestParam("file")CommonsMultipartFile[] files,
			LoadingSafetyProjectFile projectFile,HttpServletRequest request,HttpServletResponse response) throws IOException{
		ObjectMapper o = new ObjectMapper();
		Result r = new Result();
		try {
			String fileId = loadingSafetyProjectService.insertProjectFile(files, projectFile);
			r.setStatus(200);
			r.setData(fileId);
		} catch (Exception e) {
			r.setStatus(500);
			r.setMsg(e.getMessage());
			logger.error("insert insertProjectFile error "+e.getMessage());
		}
		String resultJSON = o.writeValueAsString(r);
		if(logger.isDebugEnabled()){
			logger.debug(resultJSON);
		}
		response.setCharacterEncoding("UTF-8");
		response.getWriter().print(resultJSON);
	}

3、后台接口实现类

@Override
	@Transactional
	public String insertProjectFile(CommonsMultipartFile[] files, LoadingSafetyProjectFile projectFile) throws IOException {
		RbacUser user = (RbacUser) SecurityUtils.getSubject().getPrincipal();
		String lspId = new String();
		if("".equals(projectFile.getLoadingSafetyProjectId()) || projectFile.getLoadingSafetyProjectId() == null) {
			lspId = "LSP" + StringTools.getUUID();
		}else {
			lspId = projectFile.getLoadingSafetyProjectId();
		}
		if(null!=files){
			 for(int i = 0;i<files.length;i++){
				 if(!files[i].isEmpty()){
					 projectFile.setLoadingSafetyProjectId(lspId);
					 String fileName = files[i].getOriginalFilename();  //文件原始名称
					 String fileType = fileName.split("[.]")[fileName.split("[.]").length-1];
					 String newName = TimeUtil.getTimeStamp()+ "." + fileType;  //文件新名称
					 String filePath = "/fileUploadPath"+ loadingSafetyProjectFileUploadPath;
					 FileUtil.upFile(files[i].getInputStream(), newName, fileUploadPath + loadingSafetyProjectFileUploadPath);
					 projectFile.setId(UUID.randomUUID().toString().replace("-", "")); //附件信息id
					 projectFile.setOperateUser(user.getUserId());
					 projectFile.setOldFileName(fileName);
					 projectFile.setNewFileName(newName);
					 projectFile.setFileUrl(filePath);
					 projectFile.setOperateTime(new Date());
					 projectFile.setValidFlag("1");
					 loadingSafetyProjectFileMapper.insertSelective(projectFile);
				 }
			 }
		}
		return lspId;
	}

4、工具类FileUtil.java

package com.platform.common.utils;

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.io.UnsupportedEncodingException;

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

import org.apache.log4j.Logger;

public class FileUtil {
	private static Logger logger = Logger.getLogger(FileUtil.class);
	
	private static final String UTF_8 = "UTF-8";
	
	/**
	 * 
	 * 单个文件上传
	 * 
	 * @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 + File.separator + fileName);
		try {
			bis = new BufferedInputStream(is);
			fos = new FileOutputStream(f);
			bos = new BufferedOutputStream(fos);
			byte[] bt = new byte[2048];
			int len;
			while ((len = bis.read(bt)) > 0) {
				bos.write(bt, 0, len);
			}

		} catch (Exception e) {
			logger.error(e);
		} 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) {
				logger.error(e);
			}

		}

	}

	/**
	 * @param request
	 * @param fileNameOld
	 * @param fileNameNew
	 * @param response
	 * @param filePath
	 */
	public static void downloadFile(HttpServletRequest request,String fileNameOld,String fileNameNew,HttpServletResponse response,String filePath) {
		String fileName2 = "";
		try {
			fileName2 = new String(fileNameOld.replace(" ", "").getBytes(UTF_8),"iso-8859-1");
		} catch (Exception e1) {
			logger.error(e1);
		}
		response.setCharacterEncoding(UTF_8);
		response.setContentType("application/octet-stream;charset=UTF-8");
		response.setHeader("Content-disposition", "attachment; filename="+ fileName2);

		InputStream inputStream = null;
		try {
			File file = new File(filePath +File.separator+fileNameNew);
			if (null != file && file.isFile()) {
				inputStream = new FileInputStream(file);
				OutputStream os = response.getOutputStream();
				byte[] b = new byte[2048];
				int length;
				while ((length = inputStream.read(b)) > 0) {
					os.write(b, 0, length);
				}
				os.close();
			}else {
				throw new RuntimeException("文件不存在!");
			}
		} catch (Exception e) {
			throw new RuntimeException("下载失败!");
		}finally {
			try {
				if (inputStream != null) {
					inputStream.close();
				}
			} catch (IOException e2) {
				logger.error(e2);
			}
		}
	}
	/**
	 * 下载(下载模板)
	 * @param request
	 * @param fileName
	 * @param response
	 * @return
	 */
	public static void downloadFile1(HttpServletRequest request,String fileName,HttpServletResponse response,String filePath) {
		String filename1 = null;
		try {
			filename1 = new String(fileName.getBytes(UTF_8),"iso-8859-1");
		} catch (UnsupportedEncodingException e1) {
			logger.error(e1);
		}
		response.setCharacterEncoding(UTF_8);
		response.setContentType("application/octet-stream;charset=UTF-8");
		response.setHeader("Content-disposition", "attachment; filename="+ filename1);
		InputStream inputStream = null;
		try {
			File file = new File(filePath + File.separator + fileName);
			if (null != file && file.isFile()) {
				inputStream = new FileInputStream(file);
				OutputStream os = response.getOutputStream();
				byte[] b = new byte[2048];
				int length;
				while ((length = inputStream.read(b)) > 0) {
					os.write(b, 0, length);
				}
				os.close();
			}else {
				throw new RuntimeException("文件不存在!");
			}
		} catch (Exception e) {
			throw new RuntimeException("下载失败!" + e.getMessage());
		}finally {
			try {
				if (inputStream != null) {
					inputStream.close();
				}
			} catch (IOException e2) {
				logger.error(e2);
			}
		}
	}
	
	/**
     * 删除文件
     * @param fileName
     */
    public static void delFile(String fileName) {
        try {
            String filePath = fileName;
            File delFile = new File(filePath);
            if(delFile.exists()&&delFile.isFile()){
            	if (!delFile.delete()) {
					logger.error("文件删除失败!");
				}
            }
        } catch (Exception e) {
        	throw new RuntimeException("删除文件失败!");
        }
    }
}

5、实现效果
在这里插入图片描述
在这里插入图片描述

  • 0
    点赞
  • 4
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值