Java很簡單的文件上傳(transferTo方式)


采用file.Transto 來保存上傳的文件,代碼簡單,速度快。

直接上代碼:

package com.springbootemaildemo.controller;

import com.springbootemaildemo.entity.ResponseEntity;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.multipart.MultipartFile;

import java.io.File;
import java.io.IOException;
import java.util.Date;

@RestController
@RequestMapping("/file")
@Api("文件操作")
public class FileController {
    private static final Logger logger = LoggerFactory.getLogger(FileController.class);

    @ApiOperation("文件上傳")
    @PostMapping("/upload")
    public ResponseEntity uploadFile(@RequestParam("file") MultipartFile file) {
        long startTime = System.currentTimeMillis();
        String path = "";
        String originalFilename = file.getOriginalFilename();
        logger.info("fileName:" + originalFilename);
        int lastIndexOf = originalFilename.lastIndexOf(".");
        String fileType = originalFilename.substring(lastIndexOf + 1);
        //文件類型判斷 doc,docx,jpg,png,xls
        logger.info("截取文件名類型:{}", fileType);
        if (fileType.equals("jpg") || fileType.equals("png") || fileType.equals("dox") || fileType.equals("docx") || fileType.equals("xls")) {
            path = "D:/filesss/" + new Date().getTime() + originalFilename;
            File newFile = new File(path);
            //通過CommonsMultipartFile的方法直接寫文件(注意這個時候)
            try {
                file.transferTo(newFile);
                long endTime = System.currentTimeMillis();
                logger.info("采用file.Transto的運行時間:" + String.valueOf(endTime - startTime) + "ms");
            } catch (IOException e) {
                e.printStackTrace();
            }
        } else {
            return new ResponseEntity("500", "不允許該" + fileType + "文件類型上傳", "fail");
        }
        return new ResponseEntity("200", path, "success");
    }
}

 

 

 


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM