上传文件(springMVc)

一、pom依赖


    commons-fileupload
    commons-fileupload
    1.3.1


    commons-io
    commons-io
    2.5

二、spring xml相关配置

# 上传文件大小限制(100MB)
# 1KB=1024;1MB=1048576;1GB=1073741824
upload.file.size=104857600
Spring公共配置
        
    
    
    ........
    
    
    
        
    
    

三、java代码

全局异常处理器

import com.alibaba.fastjson.JSONException;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Component;
import org.springframework.web.bind.annotation.ControllerAdvice;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.multipart.MaxUploadSizeExceededException;
import java.text.ParseException;
​
/**
 * 全局异常处理器,处理新增的异常,对于有特殊逻辑的返回直接定义个新方法,参考ServiceException
 * @author da.dong
 */
@ControllerAdvice
@Component
@ResponseBody
public class GlobalExceptionHandler {
    
    private final static Logger LOGGER = LoggerFactory.getLogger(GlobalExceptionHandler.class);
​
    @Value("${upload.file.size}")
    private int fileSize;
​
    @ExceptionHandler(MaxUploadSizeExceededException.class)
    public Result handlerMaxUploadSizeExceededException(MaxUploadSizeExceededException e){
        return new Result("error", "文件超过最大限制(" + fileSize / (1024 * 1024) + "MB)", "", "", "500");
    }
​
    @ExceptionHandler(ServiceException.class)
    public Result handlerServiceException(ServiceException e){
        return new Result("error", e.getMessage(), "", "", e.getCode());
    }
​
    @ExceptionHandler(BizException.class)
    public Result handlerBizException(BizException e){
        return new Result("error", e.getMessage(), "", "", "500");
    }
    
    //定义json报文解析异常。
    @ExceptionHandler(JSONException.class)
    public Result handlerJsonParserException(JSONException e){
        return new Result("error", "非法的JSON报文,请仔细检查", "",  "", "500");
    }
    
    //定义日期格式解析异常。
    @ExceptionHandler(ParseException.class)
    public Result handlerDateFormatParserException(ParseException e){
        return new Result("error", "日期格式非法,标准日期格式[yyyy-MM-dd HH:mm:ss]", "",  "", "500");
    }
    
    @ExceptionHandler(Exception.class)
    public Result handlerException(Exception e){
        LOGGER.error("Oops", e);
        return new Result("error", "服务器错误", "", "","500");
    }
}
​

Controller

import org.springframework.web.multipart.MultipartFile;
​
@Autowired
private HermesFileService hermesFileService;
​
@ApiVersion(group = {ApiVersionConstant.VERSION_V_1_1_0, ApiVersionConstant.VERSION_V_1_1_1_3})
@ApiOperation(value = "上传文件(仅支持docx、pdf格式文件上传)", notes = "上传文件(仅支持docx、pdf格式文件上传)")
@RequestMapping(value = "/upload", method = RequestMethod.POST)
public Result uploadFile(@RequestParam("file") MultipartFile file) {
    String ext = FileUtil.getExtension(file.getOriginalFilename());
    if(!(FileUtil.isDocx(ext) || FileUtil.isPDF(ext))){
        return ResultUtils.failed("不支持." + ext + "格式文件上传");
    }
    Result result = hermesFileService.upload(file);
    if(ObjectUtils.equals(result.getCode(), BaseConstants.SYS_SUCCESS)){
        return result;
    } else {
        return ResultUtils.failed(result.getMsg());
    }
}

Service

/**
 * 上传文件
 *
 * @param file
 * @return
 */
public Result upload(MultipartFile file) {
    String fileUrl = "";
    try {
        log.info("upload file fileName:{}, fileSize:{}", file.getOriginalFilename(), file.getSize());
        if(file.getSize() - fileSize > 0) {
            return ResultUtils.failed("文件超过最大限制(" + fileSize / (1024 * 1024) + "M)");
        }
        String ext = FastDFSUtil.getFileExtension(file.getOriginalFilename());
        fileUrl = FastDFSUtil.upload(file.getInputStream(), file.getSize(), ext, new HashMap());
    } catch (Exception e) {
        log.error("fastDFS error upload, ", e);
    }
    if (StringUtils.isNotBlank(fileUrl)) {
        return ResultModel.successResult(fileUrl);
    } else {
        return ResultUtils.failed();
    }
}

Util

import cn.hutool.core.util.ObjectUtil;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.fileupload.FileItem;
import org.apache.commons.fileupload.FileItemFactory;
import org.apache.commons.fileupload.disk.DiskFileItemFactory;
import org.apache.commons.lang3.StringUtils;
import org.springframework.web.multipart.MultipartFile;
import org.springframework.web.multipart.commons.CommonsMultipartFile;
​
import java.io.ByteArrayOutputStream;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.nio.file.FileVisitResult;
import java.nio.file.Files;
import java.nio.file.Path;
import java.nio.file.SimpleFileVisitor;
import java.nio.file.attribute.BasicFileAttributes;
​
@Slf4j
public class FileUtil {
​
/**
 * 根据文件路径获取文件后缀名
 * @param filePath : /xxx/xxxx/xxx.pdf
 * @return pdf
 */
public static String getExtension(String filePath) {
    if (StringUtils.isNotBlank(filePath)) {
        if (filePath.contains(Constants.DOT)) {
            return StringUtils.substring(filePath, StringUtils.lastIndexOf(filePath, Constants.DOT) + 1);
        } else {
            throw new ServiceException(BaseConstants.SYS_ERROR, "filePath 格式错误");
        }
    } else {
        throw new ServiceException(BaseConstants.SYS_ERROR, "filePath not empty...");
    }
}
​
/**
 * 根据文件路径获取文件的名称
 * @param filePath /group2/xxx.pdf
 * @return /group2/xxx
 */
public static String getFilePath(String filePath) {
    int index = filePath.lastIndexOf("/");
    return StringUtils.substring(filePath, 0, index);
}
​
public static String getFileName(String filePath) {
    int start = filePath.lastIndexOf("/");
    int end = filePath.lastIndexOf(getExtension(filePath));
    return StringUtils.substring(filePath, start + 1, end - 1);
}
​
public static void main(String[] args) {
    String str = "/xxx/xxd/pdf.d/pdf.pdf.pdf";
    String ext = getExtension(str);
    System.out.println("ext:" + ext);
    String filePath = getFilePath(str);
    System.out.println("filePath:"+filePath);
    String fileName = getFileName(str);
    System.out.println("fileName:"+fileName);
}
​
/**
 * true: 是word文件
 * false:不是word文件
 * @param ext:文件后缀名
 * @return
 */
public static boolean isWord(String ext){
    if (isDoc(ext) || isDocx(ext)) {
        return true;
    }
    return false;
}
​
public static boolean notIsWord(String ext){
    return !isWord(ext);
}
​
/**
 * true: 是 doc word 文件
 * false: 非 doc word 文件
 * @param ext
 * @return
 */
public static boolean isDoc(String ext){
    if (ObjectUtil.equal(Constants.doc, ext)) {
        return true;
    }
    return false;
}
​
public static boolean notIsDoc(String ext){
    return !isDoc(ext);
}
​
/**
 * true: 是 docx word 文件
 * false: 非 docx word 文件
 * @param ext
 * @return
 */
public static boolean isDocx(String ext){
    if (ObjectUtil.equal(Constants.docx, ext)) {
        return true;
    }
    return false;
}
​
public static boolean notIsDocx(String ext){
    return !isDocx(ext);
}
​
/**
 * true: 是pdf文件
 * false:不是pdf文件
 * @param ext:文件后缀名
 * @return
 */
public static boolean isPDF(String ext){
    if (ObjectUtil.equal(Constants.pdf, ext)) {
        return true;
    }
    return false;
}
​
public static boolean notIsPDF(String ext){
    return !isPDF(ext);
}
​
/**
 * 递归删除当前文件夹里的全部内容(含当前文件夹)
 */
public static void deleteAllFiles(Path curDirPath) {
    try {
        Files.walkFileTree(curDirPath, new SimpleFileVisitor() {
            @Override
            public FileVisitResult visitFile(Path file, BasicFileAttributes attrs) throws IOException {
                Files.delete(file);
                return FileVisitResult.CONTINUE;
            }
​
            @Override
            public FileVisitResult postVisitDirectory(Path dir, IOException exc) throws IOException {
                Files.delete(dir);
                return FileVisitResult.CONTINUE;
            }
        });
    } catch (IOException e) {
        e.printStackTrace();
    }
}
}

你可能感兴趣的:(上传文件(springMVc))