spring bootweb视频图片上传

import org.springframework.util.ResourceUtils;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;
import org.springframework.web.multipart.MultipartHttpServletRequest;

import javax.servlet.http.HttpServletRequest;
import java.io.*;
import java.nio.file.Files;
import java.util.*;

@RestController
@RequestMapping("/file")
public class UploadAction {
    /**
     * 单视频文件上传
     *
     * @param file
     * @param request
     * @return
     */
    @PostMapping("/upload_video")
    @ResponseBody
    public Map upload_video(@RequestParam("file") MultipartFile file, HttpServletRequest request) throws IOException {
        FileInputStream in = null;
        //获取跟目录
        File path = new File(ResourceUtils.getURL("classpath:").getPath());
        if(!path.exists()) path = new File("");
        System.out.println("path:"+path.getAbsolutePath());
        if (!file.isEmpty()) {
            String saveFileName = file.getOriginalFilename();
            System.out.println("文件名:"+saveFileName);
            File file1 = new File(path.getAbsolutePath(),"static/video/");
            File saveFile = new File(path.getAbsolutePath(),"static/video/"+saveFileName);

            if (!file1.exists()) {
                file1.mkdirs();

            }
            if (saveFile.exists()){
                Files.delete(saveFile.toPath());
            }
            System.out.println("upload url:"+saveFile.getAbsolutePath());
            try {
                BufferedOutputStream out = new BufferedOutputStream(new FileOutputStream(saveFile));
                out.write(file.getBytes());
                out.flush();
                out.close();
                Map map= new HashMap();
                map.put("code",0);
                map.put("msg","上传成功!");
                map.put("src","/video/"+saveFileName);
                return map ;
            } catch (FileNotFoundException e) {
                e.printStackTrace();
                return (Map) Collections.singletonList(e.getMessage());
            } catch (IOException e) {
                e.printStackTrace();
                return (Map) Collections.singletonList(e.getMessage());
            }
        } else {
            return (Map) Collections.singletonList("上传失败,因为文件为空.");
        }
    }


    /**
     * 单图片文件上传
     *
     * @param file
     * @param request
     * @return
     */
    @RequestMapping(value = "/upload_img")
    @ResponseBody
    public Map upload_img(@RequestParam("file") MultipartFile file, HttpServletRequest request) throws IOException {
        //获取跟目录
        File path = new File(ResourceUtils.getURL("classpath:").getPath());
        if(!path.exists()) path = new File("");
        System.out.println("path:"+path.getAbsolutePath());
        if (!file.isEmpty()) {
            String saveFileName = file.getOriginalFilename();
            System.out.println("文件名:"+saveFileName);
            File file1 = new File(path.getAbsolutePath(),"static/images/");
            File saveFile = new File(path.getAbsolutePath(),"static/images/"+saveFileName);

            if (!file1.exists()) {
                file1.mkdirs();

            }
            if (saveFile.exists()){
                Files.delete(saveFile.toPath());
            }
            System.out.println("upload url:"+saveFile.getAbsolutePath());
            try {
                BufferedOutputStream out = new BufferedOutputStream(new FileOutputStream(saveFile));
                out.write(file.getBytes());
                out.flush();
                out.close();
                Map map= new LinkedHashMap();
                Map map2 = new HashMap();
                map.put("code",0);
                map.put("msg","图片上传成功!");
                map2.put("src","/images/"+saveFileName);
                map2.put("title",saveFileName);

                map.put("data",map2);
                return map ;
            } catch (FileNotFoundException e) {
                e.printStackTrace();
                Map map= new HashMap();
                map.put("e",e.getMessage());
                return  map;
            } catch (IOException e) {
                e.printStackTrace();
                Map map= new HashMap();
                map.put("e",e.getMessage());
                return map;
            }
        } else {
            Map map= new HashMap();
            map.put("e","上传失败,因为文件为空.");
            return map;
        }
    }

    /**
     * 多文件上传
     *
     * @param request
     * @return
     */
    @PostMapping("/uploadFiles")
    @ResponseBody
    public String uploadFiles(HttpServletRequest request) throws IOException {
        File savePath = new File(request.getSession().getServletContext().getRealPath("/upload/"));
        if (!savePath.exists()) {
            savePath.mkdirs();
        }
        List<MultipartFile> files = ((MultipartHttpServletRequest) request).getFiles("file");
        MultipartFile file = null;
        BufferedOutputStream stream = null;
        for (int i = 0; i < files.size(); ++i) {
            file = files.get(i);
            if (!file.isEmpty()) {
                try {
                    byte[] bytes = file.getBytes();
                    File saveFile = new File(savePath, file.getOriginalFilename());
                    stream = new BufferedOutputStream(new FileOutputStream(saveFile));
                    stream.write(bytes);
                    stream.close();
                } catch (Exception e) {
                    if (stream != null) {
                        stream.close();
                        stream = null;
                    }
                    return "第 " + i + " 个文件上传有错误" + e.getMessage();
                }
            } else {
                return "第 " + i + " 个文件为空";
            }
        }
        return "所有文件上传成功";
    }
}
  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
要使用Spring Boot来实现图片的上传下载,可以使用Spring Boot提供的Multipart文件上传功能和Resource资源访问功能。 首先,在pom.xml文件中添加以下依赖: ``` <dependency> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-starter-web</artifactId> </dependency> <dependency> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-starter-webflux</artifactId> </dependency> ``` 然后,在application.properties文件中添加以下配置: ``` # 储存位置 upload.dir=/path/to/upload/dir ``` 接下来,创建一个Controller类来处理上传和下载请求: ``` import org.springframework.core.io.InputStreamResource; import org.springframework.core.io.Resource; import org.springframework.http.MediaType; import org.springframework.http.ResponseEntity; import org.springframework.stereotype.Controller; import org.springframework.util.StringUtils; import org.springframework.web.bind.annotation.*; import org.springframework.web.multipart.MultipartFile; import java.io.*; import java.nio.file.Files; import java.nio.file.Path; import java.nio.file.Paths; @Controller public class FileController { private static final String UPLOAD_DIR = "/path/to/upload/dir"; @PostMapping("/upload") public ResponseEntity<String> handleFileUpload(@RequestParam("file") MultipartFile file) { String filename = StringUtils.cleanPath(file.getOriginalFilename()); try { if (file.isEmpty()) { throw new RuntimeException("文件为空"); } if (filename.contains("..")) { throw new RuntimeException("无效的文件名"); } try (InputStream inputStream = file.getInputStream()) { Files.copy(inputStream, Paths.get(UPLOAD_DIR).resolve(filename)); } } catch (IOException e) { throw new RuntimeException("上传失败"); } return ResponseEntity.ok("上传成功"); } @GetMapping("/download") public ResponseEntity<Resource> serveFile(@RequestParam("filename") String filename) { Path file = Paths.get(UPLOAD_DIR).resolve(filename); Resource resource = null; try { resource = new InputStreamResource(Files.newInputStream(file)); } catch (IOException e) { throw new RuntimeException("文件不存在"); } return ResponseEntity.ok() .contentLength(file.toFile().length()) .contentType(MediaType.parseMediaType("application/octet-stream")) .body(resource); } } ``` 在上面的Controller类中,我们使用了MultipartFile来接收上传的文件,并使用Files.copy方法将文件复制到指定的目录下。在下载文件时,我们使用了Resource和InputStreamResource来读取文件内容,并将其包装成ResponseEntity对象返回给客户端。 最后,启动应用程序,可以使用以下命令上传文件: ``` curl -F "file=@/path/to/file.jpg" http://localhost:8080/upload ``` 也可以使用以下命令下载文件: ``` curl -OJ http://localhost:8080/download?filename=file.jpg ``` 其中,-O选项表示将文件保存到本地,-J选项表示使用文件名作为保存文件的名称。

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值