SpringBoot--实战开发--文件上传(五十)

一、input上传

  1. 前端页面
<template>
  <div>
    <li>
      <h3>添加新图:</h3>
      <input type="text" v-model="name" />
      <br />
      <br />
      <input
        type="file"
        id="saveImage"
        name="photo"
        accept="image/png, image/gif, image/jpeg"
        ref="new_image"
      />
      <br />
      <br />
      <el-button @click="addImage">确认添加</el-button>
    </li>
  </div>
</template>
<script>
import axios from "axios";

export default {
  data() {
    return { name: "" };
  },
  components: {},
  methods: {
    addImage: function() {
      let self = this;
      if (self.$refs.new_image.files.length !== 0) {
        let formData = new FormData();
        // 文本框数据
        formData.append("name", this.name);
        // 通过append向form对象添加数据
        formData.append("image_data", self.$refs.new_image.files[0]);
        //单个文件进行上传

        axios
          .post("http://localhost:8888/upload", formData, {
            "Content-Type": "multipart/form-data"
          })
          .then(response => {
            console.log(response.data);
          });
      }
    }
  }
};
</script>

界面:


前端界面
  1. 后端控制器
@RestController
@RequestMapping("/upload")
@CrossOrigin
public class UploadController {

    @PostMapping
    public Map<String, Object> upload(@RequestParam(name = "image_data")
                                              MultipartFile file,
                                      @RequestParam(name = "name") String name) {
        Map<String, Object> map = new HashMap<>();
        // 文件上传
        if (!file.isEmpty()) {
            try {
                Resource resource = new ClassPathResource("/");
                String path = resource.getFile().getPath();
                // 获取resources路径,并获取文件名
                String newCompanyImagepath = path+"/" + file.getOriginalFilename();
                // 创建文件对象
                File newFile = new File(newCompanyImagepath);
                if (!newFile.exists()) {
                    newFile.createNewFile();
                }
                System.out.println(name);
                System.out.println(newFile.getAbsoluteFile());
                // 获取输出流
                BufferedOutputStream out = new BufferedOutputStream(
                        new FileOutputStream(newFile));
                out.write(file.getBytes());
                out.flush();
                out.close();
            } catch (FileNotFoundException e) {
                e.printStackTrace();
                map.put("msg", "图片上传失败");
                return map;
            } catch (IOException e) {
                e.printStackTrace();
                map.put("msg", "图片上传失败");
                return map;
            }
        }
        map.put("msg", "上传成功");
        return map;
    }
}

上传结果
上传结果

二、 element ui--Upload 组件上传

  1. 前端页面
<template>
  <el-upload
    class="avatar-uploader"
    action="http://localhost:8888/upload"
    :show-file-list="false"
    :on-success="handleAvatarSuccess"
    :before-upload="beforeAvatarUpload"
  >
    <!-- 显示图片 -->
    <img v-if="imageUrl" :src="imageUrl" class="avatar" />
    <i v-else class="el-icon-plus avatar-uploader-icon"></i>
  </el-upload>
</template>
<script>

export default {
  data() {
    return { imageUrl: "" };
  },
  components: {},
  methods: {
    // 头像处理
    handleAvatarSuccess(res, file) {
      this.imageUrl = URL.createObjectURL(file.raw);
    },
    beforeAvatarUpload(file) {
      const isJPG = file.type === "image/jpeg";
      // 文件大小
      const isLt2M = file.size / 1024 / 1024 < 2;
      // 文件判断
      if (!isJPG) {
        this.$message.error("上传头像图片只能是 JPG 格式!");
      }
      if (!isLt2M) {
        this.$message.error("上传头像图片大小不能超过 2MB!");
      }
      return isJPG && isLt2M;
    }
  }
};
</script>
前端页面
  1. 后端 控制器
@RestController
@RequestMapping("/upload")
@CrossOrigin
public class UploadController {

    @PostMapping
    public Map<String, Object> upload(MultipartFile file) {
        Map<String, Object> map = new HashMap<>();
        // 文件上传
        if (!file.isEmpty()) {
            try {
                Resource resource = new ClassPathResource("/");
                String path = resource.getFile().getPath();
                // 获取resources路径,并获取文件名
                String newCompanyImagepath = path+"/" + file.getOriginalFilename();
                // 创建文件对象
                File newFile = new File(newCompanyImagepath);
                if (!newFile.exists()) {
                    newFile.createNewFile();
                }
                System.out.println(newFile.getAbsoluteFile());
                // 获取输出流
                BufferedOutputStream out = new BufferedOutputStream(
                        new FileOutputStream(newFile));
                out.write(file.getBytes());
                out.flush();
                out.close();
            } catch (FileNotFoundException e) {
                e.printStackTrace();
                map.put("msg", "图片上传失败");
                return map;
            } catch (IOException e) {
                e.printStackTrace();
                map.put("msg", "图片上传失败");
                return map;
            }
        }
        map.put("msg", "上传成功");
        return map;
    }
}

上传结果

上传结果

二、 上传示例

  1. 前端代码
<template>
  <!-- 图片上传 -->
  <div>
          <el-upload
            ref="upload"
            action="http://localhost:8888/goodsPic"
            list-type="picture-card"
            :on-preview="handlePictureCardPreview"
            :on-success="handlePictureSuccess"
            :on-remove="handleRemove"
          >
            <i class="el-icon-plus"></i>
          </el-upload>
  </div>
</template>
<script>
export default {
  data() {
    return {
      images: []    
     };
  },
  methods: {
    handlePictureSuccess(response, file) {
      // 图片内容
      // console.log( URL.createObjectURL(file.raw));
      // 向数组添加图片
      this.images.push(response.msg);
      console.log(response.msg);
    },
    // 移除图片
    handleRemove(file, fileList) {
      // 删除数据
      this.images.forEach((item, index) => {
        if (file.response.msg == item) {
          this.images.splice(index, 1);
        }
      });
      console.log(this.images);
      console.log(file.response.msg);
      console.log(file, fileList);
    },
    // 浏览图片
    handlePictureCardPreview(file) {
      console.log(file);
    }
  }
};
</script>
  1. 后端控制器
    配置路径:
# 文件上传路径
upload.path=images

控制器:

@RestController
@RequestMapping(value = "/goodsPic", produces = {"application/json;charset=UTF-8"})
@CrossOrigin
@Slf4j
public class GoodsPicController {
    @Value("${upload.path}")
    private String uploadFolder;
    @Autowired
    private GoodsPicService goodsPicService;

    /**
     * MultipartFile:SpringMVC的multipartFile对象,用于接收前端请求传入的FormData。
     * @param file
     * @return
     */
    @PostMapping
    public Result upload(MultipartFile file) {
        if (Objects.isNull(file) || file.isEmpty()) {
            log.error("文件为空");
            return Result.ok("件为空,请重新上传");
        }
        try {
            byte[] bytes = file.getBytes();
            // 获取类路径
            Resource resource=new ClassPathResource("/");
            String strPath=resource.getFile().getPath();
            // 定义一个上传路径
            String fileName=file.getOriginalFilename();
            fileName=UUID.randomUUID().toString().replace("-","")
                    +fileName.substring(fileName.indexOf("."),fileName.length());
            Path path= Paths.get(strPath+"/"+uploadFolder+"/"+fileName);
            // 如果没有files文件夹,则创建
            if (!Files.isWritable(path)) {
                Files.createDirectories(Paths.get(strPath+"/"+uploadFolder));
            }
            //文件写入指定路径
            Files.write(path, bytes);
            return  Result.ok(fileName);
        } catch (IOException e) {
            return Result.ok("上传失败"+e.getMessage());
        }
    }
}
  1. 上传测试


    图片上传

    上传结果

三、PostMan测试

文件上传配置
选择文件
上传成功
最后编辑于
©著作权归作者所有,转载或内容合作请联系作者
平台声明:文章内容(如有图片或视频亦包括在内)由作者上传并发布,文章内容仅代表作者本人观点,简书系信息发布平台,仅提供信息存储服务。

推荐阅读更多精彩内容

  • 上传模块配置样例: # 上传大小限制(包括所有内容) client_max_body_size 100m; # 上...
    SkTj阅读 13,211评论 0 3
  • 基于Vue的一些资料 内容 UI组件 开发框架 实用库 服务端 辅助工具 应用实例 Demo示例 element★...
    尝了又尝阅读 1,190评论 0 1
  • 前端开发面试题 面试题目: 根据你的等级和职位的变化,入门级到专家级,广度和深度都会有所增加。 题目类型: 理论知...
    怡宝丶阅读 2,615评论 0 7
  • 周检视0617~0623 #相信我能比我真的能更重要!# 【宝宝的90天目标】: ①早睡早起(21:00-07:0...
    丰伟霞sharily阅读 244评论 0 1
  • 皇帝的衣服打一个字,袭。 建议大家尝试要睡早起,多运动,不抽烟不喝酒,不吃夜宵,养成一个良好的习惯。久而久之,你就...
    嗨喽呦阅读 158评论 0 0