返回顶部

SpringMVC文件上传

package com.gps808.inspect.controller;

import com.framework.web.annotation.NotLogin;
import com.framework.web.dto.AjaxResult;
import com.gps808.inspect.vo.InspectFileVo;
import com.gps808.report.action.base.StandardReportBaseAction;
import org.apache.commons.lang3.StringUtils;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.multipart.MultipartFile;

import java.io.File;
import java.util.ArrayList;
import java.util.List;

/**
 * @description:
 * @author: wwy 
 * @time: 2022/8/26 13:47
 */
@NotLogin
@RestController
@RequestMapping("/inspect_file")
public class InspectFileUploadController extends StandardReportBaseAction {

    private static final long serialVersionUID = -4988160694076411531L;

    /**
     * 上传文件
     */
    @PostMapping("/upload")
    @ResponseBody
    public AjaxResult upload(MultipartFile uploadFile) throws Exception {
        String folderName = getRequestStringEx("folderName");
        if (StringUtils.isBlank(folderName)) {
            folderName = "software";
        }
        String realPath = this.getRequest().getSession().getServletContext().getRealPath("upload/") + folderName;
        //2.判断该目录是否存在
        File file = new File(realPath);
        if(!file.exists()){
            file.mkdirs();
        }
        //文件名称
        String fileName = System.nanoTime() + "_" + uploadFile.getOriginalFilename();
        File target = new File(realPath + "/" + fileName);
        //把myfile转移到目标目录下
        uploadFile.transferTo(target);
        InspectFileVo fileVo = new InspectFileVo();
        fileVo.setFilePath("/upload/" + folderName + "/" + fileName);
        List<String> jpgArray = new ArrayList<>();
        jpgArray.add("tiff");
        jpgArray.add("pjp");
        jpgArray.add("pjpeg");
        jpgArray.add("jfif");
        jpgArray.add("webp");
        jpgArray.add("tif");
        jpgArray.add("bmp");
        jpgArray.add("png");
        jpgArray.add("jpeg");
        jpgArray.add("jpg");
        jpgArray.add("gif");
        jpgArray.add("ico");
        jpgArray.add("xbm");
        jpgArray.add("dib");
        if (jpgArray.contains(this.getsuffixEx(fileName))) {
            fileVo.setFileType(1);
        } else {
            fileVo.setFileType(2);
        }
        return AjaxResult.getSuccess(null, fileVo);
    }

    /**
     * 获取后缀名
     *
     * @return
     */
    private String getsuffixEx(String fileName) {
        String[] strArray = fileName.split("\\.");
        int suffixIndex = strArray.length - 1;
        return strArray[suffixIndex].toLowerCase();
    }

    @Override
    protected boolean checkPrivi() {
        return true;
    }

}

 

posted @ 2022-09-15 17:58  不懒人  阅读(33)  评论(0编辑  收藏  举报