当前位置: 代码迷 >> 综合 >> MultipartFile 上传方法
  详细解决方案

MultipartFile 上传方法

热度:105   发布时间:2023-11-02 11:43:19.0
/*** <p class="detail">* 功能:多文件上传* </p>* @param files* @param destDir* @throws Exception* @author wangsheng* @date 2014年9月25日*/public void uploads(MultipartFile[] files, String destDir, HttpServletRequest request) throws Exception {String path = request.getContextPath();String basePath = request.getScheme() + "://" + request.getServerName() + ":" + request.getServerPort() + path;try {fileNames = new String[files.length];int index = 0;for (MultipartFile file : files) {String suffix = file.getOriginalFilename().substring(file.getOriginalFilename().lastIndexOf(".") + 1);int length = getAllowSuffix().indexOf(suffix);if (length == -1) {throw new Exception("请上传允许格式的文件");}if (file.getSize() > getAllowSize()) {throw new Exception("您上传的文件大小已经超出范围");}String realPath = request.getSession().getServletContext().getRealPath("/");File destFile = new File(realPath + destDir);if (!destFile.exists()) {destFile.mkdirs();}String fileNameNew = getFileNameNew() + "." + suffix;//File f = new File(destFile.getAbsoluteFile() + "\\" + fileNameNew);file.transferTo(f);f.createNewFile();fileNames[index++] = basePath + destDir + fileNameNew;}} catch (Exception e) {throw e;}}

  单文件上传

/***功能:文件上传* @throws Exception* @author wangsheng* @date 2016年9月8日*/public void upload(MultipartFile file, String destDir, HttpServletRequest request) throws Exception {String path = request.getContextPath();String basePath = request.getScheme() + "://" + request.getServerName() + ":" + request.getServerPort() + path;try {String suffix = file.getOriginalFilename().substring(file.getOriginalFilename().lastIndexOf(".") + 1);int length = getAllowSuffix().indexOf(suffix);if (length == -1) {throw new Exception("请上传允许格式的文件");}if (file.getSize() > getAllowSize()) {throw new Exception("您上传的文件大小已经超出范围");}String realPath = request.getSession().getServletContext().getRealPath("/");File destFile = new File(realPath + destDir);if (!destFile.exists()) {destFile.mkdirs();}String fileNameNew = getFileNameNew() + "." + suffix;File f = new File(destFile.getAbsoluteFile() + "/" + fileNameNew);file.transferTo(f);f.createNewFile();fileName = basePath + destDir + fileNameNew;} catch (Exception e) {throw e;}}

前段代码:

<form:form id="inputForm" action="后台接口" method="post" class="form-horizontal" enctype="multipart/form-data"><input type="file" name="fileZip" /><%--这个input  name的名字要和后台接口MultipartFile的接受参数名字一致--%><input type="submit" name="提交"></form:form>

后台多文件上传也可以这样写

public void upload(MultipartFile file1, MultipartFile file2,String destDir, HttpServletRequest request) throws Exception {//方法体}前端:<input type="file" name="file1" />   
<input type="file" name="file2" />