【Java-文件上传至本地/服务器】


都是平常业务需求可能会用到的,也没什么复杂逻辑。copy走就能用。
已经把import 带上了,废话不多说,上代码。

controller模块

我自己的demo用了swagger ,所以有这个@Api 注解,大家实际项目若没用swagger将@Api 、 @ApiOperation 整行删掉即可。

import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.multipart.MultipartFile;

import javax.annotation.Resource;
@RestController  
@Api(tags = "文件相关controller")  
@RequestMapping("/file")  
public class FileUploadController {
          
     
  
    @Resource  
    FileService fileService;  
  
    @ApiOperation("文件上传")  
    @PostMapping("/upload")  
    public String uploadFile(MultipartFile file){
          
     
        return fileService.fileUpload(file);  
    }  
}

service模块

import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Service;
import org.springframework.web.multipart.MultipartFile;

import java.io.File;
@Slf4j
@Service
public class FileService {
          
   
    public String fileUpload(MultipartFile file){
          
   
        final String originalFilename = file.getOriginalFilename();
        String savePath = "E:\zzj\xrk\" + originalFilename;
        try {
          
   
            createDir("E:\zzj\xrk\");
            log.info("文件开始上传......");
            file.transferTo(new File(savePath));
            log.info("上传结束......");
            return "上传完成,文件上传至:" + savePath;
        } catch (Exception ex) {
          
   
            ex.printStackTrace();
            return "文件上传异常";
        }
    }

    /**
     * 创建文件目录
     *
     * @param path
     */
    public void createDir(String path) {
          
   
        File dir = new File(path);
        if (!dir.exists()) {
          
   
            log.info("开始创建目录......");
            dir.mkdir();
        }
    }
}

运行结果

上传结果

经验分享 程序员 微信小程序 职场和发展