欢迎您访问程序员文章站本站旨在为大家提供分享程序员计算机编程知识!
您现在的位置是: 首页

springMVC文件上传

程序员文章站 2022-06-03 10:30:14
...
MultipartFile   支持所有类型文件上传

pom依赖:

 

      <properties>
       <commons-fileupload.version>1.3.1</commons-fileupload.version>
       
        <lombok.version>1.18.2</lombok.version>
      </properties>

<!-- 文件上传组件 -->
            <dependency>
                <groupId>commons-fileupload</groupId>
                <artifactId>commons-fileupload</artifactId>
                <version>${commons-fileupload.version}</version>
            </dependency>
<!--lombok 依赖-->
 <!--自动  生成 set,get-->
            <!-- https://mvnrepository.com/artifact/org.projectlombok/lombok -->
            <dependency>
                <groupId>org.projectlombok</groupId>
                <artifactId>lombok</artifactId>
                <version>${lombok.version}</version>
                <scope>provided</scope>
            </dependency>

 

springmvc配置文件上传:

<!--&lt;!&ndash; 定义文件上传解析器 &ndash;&gt;-->
	<bean id="multipartResolver"
		  class="org.springframework.web.multipart.commons.CommonsMultipartResolver">
		<!-- 设定默认编码 -->
		<property name="defaultEncoding" value="UTF-8"></property>
		<!-- 设定文件上传的最大值5MB,5*1024*1024 -->
		<property name="maxUploadSize" value="5242880"></property>
	</bean>

 

 

后台:

controller:


@Controller
@RequestMapping("/util")
public class UtilController {
    @Autowired
    FileService fileService;

    /**
     *
     * @param prefix   文件保存的分类文件夹,比如picture
     * @param file
     * @return
     * @throws Exception
     */
    @RequestMapping("/upload/{prefix}")
    @ResponseBody
    public Result<FileUploadResult> uploaFile(@PathVariable String prefix,@RequestParam("file") MultipartFile file) throws Exception {

     return fileService.pictureUpload(file,prefix);
    }
}

FileService代码:

接口层


public interface FileService {
    Result<FileUploadResult> pictureUpload(MultipartFile src, String prefix) throws Exception;
}

 

实现层:

@Service
public class FileServiceImpl implements FileService {
    @Autowired
    private HttpServletRequest request;

    //   public static  final String PICTURE_SAVE_PREFIX="picture";
    @Override
    public Result<FileUploadResult> pictureUpload(MultipartFile src, String prefix) throws Exception {

        String ipPort = "http://" + request.getRemoteHost() + ":" + request.getServerPort();
        //真实保存路径
        String realServerBasePath = request.getSession().getServletContext().getRealPath("");
        String resultPath = PictureUploadUtil.pictureUpload(ipPort, prefix, realServerBasePath, src);
        if (StringUtils.isEmpty(resultPath)) {
            return Result.error(-1, "文件上传失败");
        }
        FileUploadResult result = new FileUploadResult();
        result.setDownloadUrl(resultPath);
        return Result.success(result);
    }

}

PictureUploadUtil:


/**
 * 图片上传工具类,
 */

public class PictureUploadUtil {

    /**
     * @param prefix   各类型文件 在项目中的根文件夹名,方便分类存放  比如  /pic,如果prefix为  pic
     *                 则fileSaveDir:E:\学习文档\测试文件\pic\2018\09\19
     * @param savePath 保存文件的根目录,一般需要使用Context.getRealPath("") 来获取
     * @param src      源文件
     * @return
     */

    public static String pictureUpload(String ipPort, String prefix, String savePath, MultipartFile src) throws Exception {

        if (src.isEmpty()) {
            throw new Exception("MultipartFile is empty");
        }
        String dateDir = getDirsNameByDate(prefix);
        String fileSaveDir = savePath + dateDir;
        String newName = buildFileName(src.getOriginalFilename());
        System.out.println("fileSaveDir:" + fileSaveDir);
        //真实路径是:savePath+dateDir+newName
        //下载只需要:ip:port/dateDir/newName
        String downloadUrl = ipPort + "/" + dateDir + "/" + newName;
        File dirs = new File(fileSaveDir);
        if (!dirs.exists()) {
            dirs.mkdirs();
        }
        String realSavePath = fileSaveDir + File.separator + newName;
        System.out.println("realSavePath:" + realSavePath);
        Path path = Paths.get(realSavePath);
        try {
            Files.write(path, src.getBytes());
        } catch (IOException e) {
            downloadUrl = null;
            e.printStackTrace();
        }
        return downloadUrl;
    }

    /**
     * @param prefix 根文件夹名字(分类存放,比如  /pic)
     * @return
     */
    private static String getDirsNameByDate(String prefix) {
        Date now = new Date();
        String dateString = new SimpleDateFormat("yyyy/MM/dd").format(now).toString();
        String result = dateString;
        if (!StringUtils.isEmpty(prefix)) {
            result = prefix + File.separator + dateString;
        }

        System.out.println("getDirsNameByDate:" + result);
        return result;
    }

    /**
     * @return 获取文件名后缀
     * @created 15:26 2018/9/19
     * @author wangwei
     * @params
     */
    private static String getFileSuffix(String fileName) {
        System.out.println("fileName:" + fileName);
        if (StringUtils.isEmpty(fileName)) {
            return null;
        }
        return fileName.substring(fileName.lastIndexOf('.'));
    }

    private static void fileCopy(File source, File dest) throws IOException {
        FileChannel inputChannel = null;
        FileChannel outputChannel = null;
        try {
            inputChannel = new FileInputStream(source).getChannel();
            outputChannel = new FileOutputStream(dest).getChannel();
            outputChannel.transferFrom(inputChannel, 0, inputChannel.size());
        } finally {
            inputChannel.close();
            outputChannel.close();
        }


    }

    /**
     * @param originName
     * @return 生成文件名
     */
    private static String buildFileName(String originName) {
        return System.currentTimeMillis() + getFileSuffix(originName);
    }

   
}

返回结果封装类:


/**
*@author wangwei
*@created 14:31 2018/9/19
 *@classname FileUploadResult
*@classdescription  文件上传返回结果
*
*/
@Data
public class FileUploadResult {
    private String fileName;
    private String savePath;
    //可以下载的url
    private String  downloadUrl;
    private String   url;

}

测试:

测试效果:

以图片上传为例

(使用postman测试)

springMVC文件上传

springMVC文件上传

控制台输出:

注意红色的pic,这是我在上传路径中指定的图片文件保存根目录名)

getDirsNameByDate:pic\2018/09/19
fileName:2_abumdshahnoorshawon-lilacbreastedroller.jpg
fileSaveDir:E:\学习文档\项目\ideasvnchekcout\code\buybuybuy\build-ssm\classes\artifacts\build_ssm_Web_exploded\pic\2018/09/19
realSavePath:E:\学习文档\项目\ideasvnchekcout\code\buybuybuy\build-ssm\classes\artifacts\build_ssm_Web_exploded\pic\2018/09/19\1537360876620.jpg

返回结果:

{
    "data": {
        "fileName": null,
        "savePath": null,
        "downloadUrl": "http://127.0.0.1:8080/pic\\2018/09/19/1537360876620.jpg",
        "url": null
    },
    "msg": "操作成功",
    "code": -1,
    "success": true
}

测试浏览器访问:

springMVC文件上传

测试一个压缩包上传:

springMVC文件上传

控制台输出:

注意红色的zip,这是我在上传路径中指定的.zip文件保存根目录名)

fileName:applicationContext-shiro.zip
fileSaveDir:E:\学习文档\项目\ideasvnchekcout\code\buybuybuy\build-ssm\classes\artifacts\build_ssm_Web_exploded\zip\2018/09/19
realSavePath:E:\学习文档\项目\ideasvnchekcout\code\buybuybuy\build-ssm\classes\artifacts\build_ssm_Web_exploded\zip\2018/09/19\1537360989065.zip

返回结果:

{
    "data": {
        "fileName": null,
        "savePath": null,
        "downloadUrl": "http://127.0.0.1:8080/zip\\2018/09/19/1537360989065.zip",
        "url": null
    },
    "msg": "操作成功",
    "code": -1,
    "success": true
}

测试访问:

springMVC文件上传

真实文件保存情况:

最终看看真实的目录文件是啥样的:

springMVC文件上传

springMVC文件上传