antd的upload组件上传图片至后端项目resource文件夹

antd的upload组件上传图片至后端项目resource文件夹

前端部分

<Upload name=“logo” action=“http://localhost:9001/api/phonebook/uploadPhoto” listType=“picture”
accept=".jpg,.jpeg,.png,.JPG,.JPEG,.PNG"
maxCount={1} {…props}>
<Button icon={}>点击上传

<Form.Item
                    name="photo"
                    label="照片"
                    valuePropName="fileList"
                    getValueFromEvent={
    
    normFile}
                    extra="请上传照片"
                >
                    <Upload name="logo" action="http://localhost:9001/api/phonebook/uploadPhoto" listType="picture"
                            accept=".jpg,.jpeg,.png,.JPG,.JPEG,.PNG"
                            maxCount={
    
    1} {
    
    ...props}>
                        <Button icon={
    
    <UploadOutlined />}>点击上传</Button>
                    </Upload>
                </Form.Item>
                
  • accept=".jpg,.jpeg,.png,.JPG,.JPEG,.PNG",为限制文件格式
  • maxCount={1} ,为限制文件上传数量,=1时最新的覆盖以前的
  • name=“logo” ,后端获取的名字
  • action=“http://localhost:9001/api/phonebook/uploadPhoto” ,为后端api接口

想要获取返回值,查看官方文档里的change函数,info.file.responce获取

后端部分

@RequestMapping("/uploadPhoto")
    @ResponseBody
    public Map<Integer,String> uploadPhoto(@RequestParam("logo") MultipartFile pic) throws IOException {
    
    
        /*
         * 编码为字符串*/
        String s = Base64Utils.encodeToString(pic.getBytes());
        System.out.println("s:"+s);

        /* *
         *2.解码成字节数组
         */
        Base64.Decoder decoder = Base64.getDecoder();
        byte[] bytes = decoder.decode(s);
        System.out.println("by:"+s);

        /*
         * 3.字节流转文件
         */
        String d = System.getProperty("user.dir");
        File fileMkdir = new File(d+"\\src\\main\\resources\\img");
        if (!fileMkdir.exists()){
    
    
            fileMkdir.mkdir();
        }
        String pathName = fileMkdir.getPath() + "\\" + pic.getOriginalFilename();
        System.out.println("path"+pathName);
        FileOutputStream fos = null;
        try {
    
    
            fos = new FileOutputStream(pathName);
            fos.write(bytes);
        } catch (IOException e) {
    
    
            e.printStackTrace();
        } finally {
    
    
            if (fos != null){
    
    
                try {
    
    
                    fos.close();
                } catch (IOException e) {
    
    
                    e.printStackTrace();
                }
            }
        }
        HashMap<Integer,String> need = new HashMap<>();
        need.put(0,"img\\"+ pic.getOriginalFilename());
        return need;
    }

结果

在这里插入图片描述
springboot项目图片上传及图片路径分析(jar包形式)请看另一篇文章(╹▽╹)
https://blog.csdn.net/qq_42571665/article/details/121423941?spm=1001.2014.3001.5502.

猜你喜欢

转载自blog.csdn.net/qq_42571665/article/details/121165423