SpringBoot 上传图片

控制层代码

package net.ybchen.demo.controller;

import net.ybchen.demo.utils.JsonData;
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.FileNotFoundException;
import java.io.IOException;
import java.util.UUID;

@RestController
public class UploadController {
    @PostMapping("/upload")
    public JsonData uplaod(HttpServletRequest req, @RequestParam("file") MultipartFile file) {
        String fileName=null;
        try {
            if (file.isEmpty()) {
                return JsonData.buildError("请选择文件!");
            }
            fileName = file.getOriginalFilename();
            String suffixName = fileName.substring(fileName.lastIndexOf("."));
            if (suffixName.toLowerCase().equals(".jpg") || suffixName.toLowerCase().equals(".png")) {
                File currentFile = new File("");
                String currentFilePath = currentFile.getCanonicalPath();
                System.out.println(currentFilePath);
                fileName=UUID.randomUUID().toString().replaceAll("-","") + fileName;
                String destFileName = currentFilePath + File.separator + "uploaded" + File.separator + fileName;
                File destFile = new File(destFileName);
                destFile.getParentFile().mkdirs();
                file.transferTo(destFile);
                System.out.println(destFileName);
            } else {
                return JsonData.buildError("文件后缀不正确,请上传jpg|png格式!");
            }
        } catch (FileNotFoundException e) {
            e.printStackTrace();
            return JsonData.buildError("上传失败," + e.getMessage());
        } catch (IOException e) {
            e.printStackTrace();
            return JsonData.buildError("上传失败," + e.getMessage());
        }
        return JsonData.buildSuccess(fileName);
    }
}

前端如何访问linux上的图片呢

方式一

  配置tomcat,点我直达

方式二

  配置nginx代理,点我直达

 

posted @ 2020-11-15 13:01  陈彦斌  阅读(115)  评论(0)    收藏  举报