vue+springboot同时接收上传的文件和json(代码)

前端:templete中

<input type="file" value="" id="file" @change="uploadTest">

script中

methods: {
    uploadTest (e) {
      let formData = new FormData()
      let data = JSON.stringify({
        aa: 'xxx',
        bb: 123
      })
      formData.append('file', e.target.files[0])
      formData.append('data', new Blob([data], {type: 'application/json'})) // 同时上传文件和JSON,这里1.用动new Blob;2[data]中括号;3.必须加type,postman见本站https://blog.csdn.net/FRESHET/article/details/121286971

      //   后台测试地址
      let url = 'http://192.168.1.103:8081/upload'
      let config = {
        headers: {'Content-Type': 'multipart/form-data'}
      }
      this.$axios.post(url, formData, config).then(function (response) {
        console.log(response.data)
      })
    }
  }

后台代码:

@CrossOrigin
    @PostMapping("/upload")
    @ResponseBody
    public String upload(@RequestPart("file") MultipartFile file,@RequestPart Map<String,Object> data ) {
        if (file.isEmpty()) {
            return "上传失败,请选择文件";
        }

        String fileName = file.getOriginalFilename();
        String filePath = "E:\\vuetest\\vue_upload\\";
        File dest = new File(filePath + fileName);
        try {
            file.transferTo(dest);
            System.out.println(data.get("aa"));
            System.out.println(data.get("bb"));
            System.out.println("upload ok");
            return "上传成功";
        } catch (IOException e) {
            System.err.println(e.toString());
        }
        return "上传失败!";
    }

效果:

xxx
123
upload ok 

  • 4
    点赞
  • 8
    收藏
    觉得还不错? 一键收藏
  • 2
    评论
实现视频上传和回显,需要涉及前端页面、后端接口以及视频处理等多方面的技术。下面我将从这些方面一步一步介绍具体实现方法。 1. 前端页面 前端页面需要有一个上传视频的功能,可以使用`<input type="file">`标签实现。在上传时,可以通过`FormData`对象将视频文件和一些其他参数一起发送到后端接口。示例代码如下: ```html <template> <div> <input type="file" @change="handleFileUpload"> <button @click="uploadVideo">上传</button> <video v-if="videoUrl" :src="videoUrl" controls></video> </div> </template> <script> export default { data() { return { videoUrl: '' } }, methods: { handleFileUpload(event) { this.videoFile = event.target.files[0] }, async uploadVideo() { const formData = new FormData() formData.append('file', this.videoFile) formData.append('name', 'video') const response = await fetch('/api/upload', { method: 'POST', body: formData }) const data = await response.json() if (data.success) { this.videoUrl = data.videoUrl } } } } </script> ``` 2. 后端接口 后端接口使用SpringBoot框架,需要使用`@RestController`和`@PostMapping`注解来实现视频上传接口。接收到视频文件后,可以使用FFmpeg库来处理视频文件,将视频转换为指定格式或者提取视频的缩略图等。 ```java @RestController public class VideoController { @PostMapping("/api/upload") public ApiResponse uploadVideo(@RequestParam("file") MultipartFile file) { if (file.isEmpty()) { return ApiResponse.error("上传文件不能为空"); } try { // 保存视频文件并返回视频的URL String videoUrl = saveVideo(file); return ApiResponse.success(videoUrl); } catch (Exception e) { e.printStackTrace(); return ApiResponse.error("上传失败"); } } private String saveVideo(MultipartFile file) throws Exception { String fileName = UUID.randomUUID().toString() + ".mp4"; File dest = new File("uploads/" + fileName); file.transferTo(dest); return "http://localhost:8080/uploads/" + fileName; } } ``` 3. 视频处理 视频处理需要使用FFmpeg库来实现。在SpringBoot项目中,可以使用`ProcessBuilder`来执行FFmpeg命令。下面是一个实现视频转换为MP4格式的示例代码: ```java private void convertToMp4(String inputPath, String outputPath) throws Exception { String command = String.format("ffmpeg -i %s -c:v libx264 -preset slow -crf 22 -c:a aac -b:a 128k -movflags faststart -f mp4 %s", inputPath, outputPath); Process process = new ProcessBuilder(command.split(" ")).redirectErrorStream(true).start(); InputStream inputStream = process.getInputStream(); BufferedReader reader = new BufferedReader(new InputStreamReader(inputStream)); String line; while ((line = reader.readLine()) != null) { System.out.println(line); } process.waitFor(); reader.close(); inputStream.close(); } ``` 以上是实现视频上传和回显的基本步骤,具体实现还需要根据具体需求进行调整。
评论 2
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值