简单的Springboot上传图片生成可访问的url

controller 层

@RestController
@RequestMapping("/api/file")
public class FileController {


    @Autowired

    private FileUploadService fileUploadService;

    @PostMapping("/upload")
    @ApiOperation("文件上传")
    public String uploadFile(MultipartFile file , HttpServletRequest request) {

        String linkUrl = fileUploadService.upload(file,request);

        return  linkUrl;

    }

    }

service   层

public interface FileUploadService {

    /**
     * 上传
     *
     * @param file
     * @return
     */
    String upload(MultipartFile file, HttpServletRequest request);

    ;


实现类的代码
@Service
public class WebFileUploadServiceImpl implements FileUploadService {


    @Override
    public String upload(MultipartFile file,HttpServletRequest request) {

        String path = this.filetoMultipartFile(file,request);
        return path;

    }
    
    public String filetoMultipartFile(MultipartFile file, HttpServletRequest request){
        File f = null;
        try {
            InputStream ins = file.getInputStream();
            f = new File(file.getOriginalFilename());
            String path= inputStreamToFile(ins, f,request);
            return path;
        } catch (IOException e){
            e.printStackTrace();
        }
        return null;
    }
    public static String inputStreamToFile(InputStream ins,File file,HttpServletRequest request) {
        try {
            String strBackUrl = "http://" + request.getServerName() //服务器地址
                    + ":"
                    + request.getServerPort() ;          //端口号
            System.out.println(strBackUrl);
            //项目指定存放图片地址
            String s = IdUtil.snowId()+file.toString().substring(file.toString().length()-5);
            String filename = "E:\\upload\\src\\main\\resources\\static\\image\\"+s;
            OutputStream os = new FileOutputStream(filename);
            int bytesRead = 0;
            byte[] buffer = new byte[8192];
            while ((bytesRead = ins.read(buffer, 0, 8192)) != -1) {
                os.write(buffer, 0, bytesRead);
            }
            os.close();
            ins.close();
            return strBackUrl+"/image/"+s;
        } catch (Exception e) {
            e.printStackTrace();
        }
        return null;
    }
}

生成地址 http://ip:端口/image/6078781770886840324.jpg

设置热部署5秒重启服务器就可以查看图片

spring2.x版本设置上传图片大小

#单个文件大小

spring.servlet.multipart.max-file-size = 100MB

#请求文件大小

spring.servlet.multipart.maxRequestSize= 100MB

 

  • 1
    点赞
  • 4
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
### 回答1: 下面是一个简单的 Spring Boot 上传图片的代码示例: 1. 创建一个 Controller 类,用于处理图片上传请求: ``` @RestController public class ImageController { @PostMapping("/images") public String uploadImage(@RequestParam("image") MultipartFile image) { // 存储图片 // ... return "图片上传成功"; } } ``` 2. 在 application.properties 文件中配置文件上传的相关参数: ``` spring.servlet.multipart.max-file-size=10MB spring.servlet.multipart.max-request-size=10MB ``` 3. 使用 postman 等工具,以 multipart/form-data 的格式发送图片上传请求即可。 这只是一个简单的代码示例,实际应用中还可以加入图片验证、存储方式等功能。 ### 回答2: 以下是一个使用Spring Boot上传图片简单示例代码: 1. 首先,需要在pom.xml文件中添加以下依赖项以支持文件上传功能: ```xml <dependency> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-starter-web</artifactId> </dependency> <dependency> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-starter-thymeleaf</artifactId> </dependency> <dependency> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-starter-websocket</artifactId> </dependency> ``` 2. 创建一个Controller类来处理文件上传相关的请求: ```java import org.springframework.stereotype.Controller; import org.springframework.ui.Model; import org.springframework.util.StringUtils; import org.springframework.web.bind.annotation.*; import org.springframework.web.multipart.MultipartFile; import org.springframework.web.servlet.mvc.support.RedirectAttributes; import java.io.File; import java.io.IOException; @Controller public class FileUploadController { // 处理上传文件的GET请求 @GetMapping("/") public String uploadForm() { return "upload"; } // 处理文件上传的POST请求 @PostMapping("/") public String uploadFile(@RequestParam("file") MultipartFile file, RedirectAttributes redirectAttributes) { if (file.isEmpty()) { redirectAttributes.addFlashAttribute("message", "请选择一个文件进行上传"); return "redirect:/"; } try { // 获取上传文件的原始名称 String fileName = StringUtils.cleanPath(file.getOriginalFilename()); // 设置文件存储路径 String uploadDir = "D:/uploads/"; String filePath = uploadDir + fileName; File dest = new File(filePath); file.transferTo(dest); redirectAttributes.addFlashAttribute("message", "文件上传成功"); } catch (IOException e) { e.printStackTrace(); redirectAttributes.addFlashAttribute("message", "文件上传失败"); } return "redirect:/"; } } ``` 3. 创建一个upload.html用于展示上传表单和上传结果: ```html <!DOCTYPE html> <html xmlns:th="http://www.thymeleaf.org"> <head> <meta charset="UTF-8"> <title>文件上传</title> </head> <body> <h3>文件上传</h3> <form th:action="@{/}" method="post" enctype="multipart/form-data"> <input type="file" name="file"/><br><br> <input type="submit" value="上传"/> </form> <br><br> <div th:if="${message}"> <p th:text="${message}"></p> </div> </body> </html> ``` 4. 启动Spring Boot应用程序,访问http://localhost:8080/即可看到上传表单。选择要上传的文件,并点击"上传"按钮即可完成文件上传。 注意:以上示例代码将文件存储在本地磁盘的"D:/uploads/"目录下,需要确保该目录存在且有写入权限。在实际应用中,应根据项目需求选择合适的文件存储方式。 ### 回答3: SpringBoot 是一种基于Spring框架的开源、轻量级的Java开发框架,提供了一种快速开发、轻量级、简单易用的方式来构建Java应用程序。下面是一个使用SpringBoot上传图片的示例代码。 首先,需要在pom.xml文件中添加相关依赖: ```xml <dependency> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-starter-web</artifactId> </dependency> <dependency> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-starter-websocket</artifactId> </dependency> ``` 然后,在application.properties(或application.yml)中配置上传文件路径: ```yaml spring.servlet.multipart.enabled=true spring.servlet.multipart.file-size-threshold=2KB spring.servlet.multipart.max-file-size=200MB spring.servlet.multipart.max-request-size=215MB spring.servlet.multipart.location=/path/to/save/uploaded/files ``` 在SpringBoot的入口类中添加@EnableAutoConfiguration注解来启用自动配置,然后创建一个上传文件的Controller类: ```java @RestController public class FileUploadController { @PostMapping("/upload") public String handleFileUpload(@RequestParam("file") MultipartFile file) { if (file.isEmpty()) { return "请选择文件上传"; } try { // 获取文件名 String fileName = file.getOriginalFilename(); // 获取文件的后缀名 String suffixName = fileName.substring(fileName.lastIndexOf(".")); // 重新生成文件名,防止文件重名 fileName = UUID.randomUUID().toString() + suffixName; // 设置文件存储路径 String filePath = "/path/to/save/uploaded/files/" + fileName; // 将文件保存到指定路径 file.transferTo(new File(filePath)); return "文件上传成功"; } catch (IOException e) { e.printStackTrace(); } return "文件上传失败"; } } ``` 在以上代码中,我们使用了@PostMapping注解将方法映射到上传文件的URL路径 "/upload"。通过@RequestParam注解获取上传的文件,并根据需要进行文件名的处理。然后,将文件保存到指定路径。 最后,启动SpringBoot应用程序,访问 http://localhost:8080/upload,选择文件并点击上传按钮,即可实现文件上传功能。 这就是一个简单的使用SpringBoot实现文件上传的示例代码。根据具体的需求,可能需要在代码中添加一些验证逻辑或处理上传文件的其他操作。

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值