Spring Boot文件上传

版权声明:本文为博主原创文章,未经博主允许不得转载。 https://blog.csdn.net/stSahana/article/details/83622515

spring boot 2.0.5
要实现文件上传并直接访问(查看/下载)

配置静态文件路径

application.properties

uploadPath=/opt/data1/uploads/
## 上传路径设置为静态资源路径,可以通过http直接访问,比如图片/pdf会直接显示在浏览器,word/excell会直接下载
spring.resources.static-locations=classpath:/META-INF/resources/, classpath:/resources/, classpath:/static/, classpath:/public/,file:${uploadPath}

上传接口

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.multipart.MultipartFile;

import javax.servlet.http.HttpServletRequest;
import java.io.File;
import java.io.IOException;
import java.nio.file.Files;
import java.nio.file.Path;
import java.nio.file.Paths;

/**
 * 文件上传
 *
 * @Author:sahana
 */
@RestController @Slf4j public class UploadController {

  @Value("${uploadPath}") String uploadPath;
  String DIPLOMA = "diploma";
  
  @PostMapping("/upload") public String upload(@PathVariable("id") Integer id,
      @RequestParam("file") MultipartFile file, HttpServletRequest request) {
    if (!file.isEmpty()) {
      try {
        // Get the file and save it somewhere
        byte[] bytes = file.getBytes();
        File dir = new File(uploadPath + File.separator + DIPLOMA + File.separator + id);
        if (!dir.exists())
          dir.mkdirs();
        else {
          FileUtils.deleteDirectory(dir);
          dir.mkdirs();
        }
        //        // 写文件到服务器
        //        File serverFile = new File(dir.getAbsolutePath()+File.separator+file.getOriginalFilename());
        //        file.transferTo(serverFile);
        Path path = Paths
            .get(uploadPath + DIPLOMA + File.separator + id, file.getOriginalFilename());
        Files.copy(file.getInputStream(), path);
        // String outPath=File.separator + DIPLOMA + File.separator + id + File.separator + file
         //   .getOriginalFilename()
        // 通过 http://{ip}:{port}/{outPath} 能直接访问资源
        return "上传成功";
      } catch (IOException e) {
        log.error("")
        return "上传失败";
      }
    } else {
      return "空文件";
    }
  }

}

猜你喜欢

转载自blog.csdn.net/stSahana/article/details/83622515