ant design pro上传图片到后端

本文详细介绍了如何使用Ant Design Pro的Upload组件结合后端服务,实现图片上传至阿里云OSS的功能。从前端组件配置、自定义上传逻辑到后端处理流程及OSS直链获取,全面解析了图片上传的技术细节。

我们这里是前端将图片上传到后端,然后后端这里再上传到阿里云的OSS,并返回一个文件的路径给前端

先看效果

image.png上传后生成的图片image.png

前端:

// pageList.js
const props = {
    name: "avatar",
    listType: "picture-card",
    className: "avatar-uploader",
    showUploadList: false,
    // 设置只上传一张图片,根据实际情况修改
    customRequest: info => {
      // 手动上传
      const formData = new FormData();
      formData.append('file', info.file);
      uploadLogoImg(formData);
    },
    onRemove: file => {
      // 删除图片调用
      this.setState(state => {
        const index = state.fileList.indexOf(file);
        const newFileList = state.fileList.slice();
        newFileList.splice(index, 1);
        return {
          fileList: newFileList,
        };
      });
    },

    beforeUpload: file => {
      // 控制上传图片格式
      const isJpgOrPng = file.type === 'image/jpeg' || file.type === 'image/png';

      if (!isJpgOrPng) {
        message.error('您只能上传JPG/PNG 文件!');
        return;
      }
      const isLt2M = file.size / 1024 / 1024 < 2;
      if (!isLt2M) {
        message.error('图片大小必须小于2MB!');
        return;
      }
    },
  }

...

<Upload
	{...props}
>
  {logoUrl ? <img src={logoUrl} alt="avatar" style={{ width: '100%' }} /> : uploadButton}
</Upload>

// model.js
// 上传图片logo
*uploadLogoImg({ payload }, { call, put }) {
  const response = yield call(uploadLogoImg, payload);
  yield put({
    type: 'handleUploadLogoImg',
    payload: {
      response
    },
  });
},

// api.js
export async function uploadLogoImg(params) {
  // console.log('cityApi.pageList 发送的参数');
  // console.log(JSON.stringify(params));
  return request(`${path}/uploadImage`, {
    method: 'POST',
    body: params,
  });
}

后端:

/**
 * 图片上传
 */
@PostMapping(value = "uploadImage")
public Response<String> uploadImage(LogoPicReq logoPicReq) {
  return success(appservice.uploadLogo(logoPicReq.getFile()));
}

注意:

这里的 LogoPicReq 没有@RequestBody,因为这里是通过表单提交的

@Data
public class LogoPicReq {

    private MultipartFile file;
}

OSS的代码

			if (appFile == null) {
            throw new BusinessException("数据为空");
        }
        String endpoint = ossProperties.getEndpoint();
        String accessKeyId = ossProperties.getAccessKeyId();
        String accessKeySecret = ossProperties.getAccessKeySecret();
        String bucketName = ossProperties.getBucketName();

        InputStream fileContent;
        try {
            fileContent = appFile.getInputStream();
            //获取图片名称
            String filename = appFile.getOriginalFilename();
            if (null == filename || "".equals(filename)) {
                throw new BusinessException("文件为空");
            }

            //获取图片扩展名
            String ext = filename.substring(filename.lastIndexOf(".") + 1);
            //生成图片的存放在服务器的路径
            String picName = "img/walle/" + UUID.randomUUID().toString() + "." + ext;

            OSS ossClient = new OSSClientBuilder().build(endpoint, accessKeyId, accessKeySecret);
            ossClient.putObject(bucketName, picName, fileContent);
            ossClient.shutdown();

            //获取OSS生成的url
            Date date = new Date();
            date.setTime(date.getTime() + 100L * 365 * 24 * 3600 * 1000);
            GeneratePresignedUrlRequest request = new GeneratePresignedUrlRequest(bucketName, picName, HttpMethod.GET);
            request.setExpiration(date);
            URL signedUrl = ossClient.generatePresignedUrl(request);
            log.info("[生成OSS直链]对象名:{},直链地址:{}", picName, signedUrl.toString());
            return signedUrl.toString();
        } catch (IOException e) {
            e.printStackTrace();
        }
        return null;

其中一定要通过直联的方式进行获取,否则就是上报没有权限

参考:

https://blog.youkuaiyun.com/qq_38209894/article/details/99729502

参考2

https://qdhaiqiang.github.io/2019/03/14/Ant%20Design%20Pro%E5%AD%A6%E4%B9%A0%E4%B9%8B%E4%BD%BF%E7%94%A8upload%E7%BB%84%E4%BB%B6%E5%B9%B6%E7%94%A8form%E8%A1%A8%E5%8D%95%E6%8F%90%E4%BA%A4/

Ant Design Pro 的 `Upload` 组件中,Java 后端返回的响应格式需要符合特定的结构,以便前端能够正确解析上传结果。通常,`Upload` 组件期望后端返回的响应是一个 JSON 对象,其中包含文件上传后的 URL、文件名、状态等信息。 以下是一个典型的 Java 后端返回值示例(假设使用 Spring Boot 框架): ```java import org.springframework.http.ResponseEntity; import org.springframework.web.bind.annotation.PostMapping; import org.springframework.web.bind.annotation.RequestParam; import org.springframework.web.bind.annotation.RestController; import org.springframework.web.multipart.MultipartFile; import java.io.File; import java.io.IOException; import java.nio.file.Files; import java.nio.file.Path; import java.nio.file.Paths; import java.util.HashMap; import java.util.Map; @RestController public class FileUploadController { private static final String UPLOAD_DIR = "uploads/"; @PostMapping("/upload") public ResponseEntity<Map<String, Object>> uploadFile(@RequestParam("file") MultipartFile file) { Map<String, Object> response = new HashMap<>(); try { // 确保上传目录存在 File dir = new File(UPLOAD_DIR); if (!dir.exists()) { dir.mkdirs(); } // 保存文件到服务器 byte[] bytes = file.getBytes(); Path path = Paths.get(UPLOAD_DIR + file.getOriginalFilename()); Files.write(path, bytes); // 构建返回值 response.put("success", true); response.put("data", Map.of( "url", "/uploads/" + file.getOriginalFilename(), "name", file.getOriginalFilename(), "uid", file.getName() )); response.put("errorCode", 0); response.put("errorMessage", ""); } catch (IOException e) { e.printStackTrace(); response.put("success", false); response.put("data", null); response.put("errorCode", 1); response.put("errorMessage", "文件上传失败"); } return ResponseEntity.ok(response); } } ``` ### 代码解释: 1. **`@RestController`**:表示该类是一个控制器,返回值直接写入 HTTP 响应体中。 2. **`@PostMapping("/upload")`**:处理 POST 请求,路径为 `/upload`。 3. **`MultipartFile`**:用于接收上传的文件。 4. **`Files.write(path, bytes)`**:将上传的文件写入服务器的指定目录。 5. **`response` Map**:构建返回给前端的 JSON 响应对象,包含: - `success`: 上传是否成功(布尔值)。 - `data`: 成功时返回的文件信息,包括 `url`(文件访问路径)、`name`(文件名)、`uid`(文件唯一标识)。 - `errorCode`: 错误代码,0 表示成功,非 0 表示失败。 - `errorMessage`: 错误信息,成功时为空字符串。 ### Ant Design Pro Upload 组件配置示例: ```tsx import { Upload, Button } from 'antd'; import { UploadOutlined } from '@ant-design/icons'; const MyUploadComponent = () => { const props = { name: 'file', action: '/upload', // 后端接口地址 headers: { authorization: 'Bearer your_token', // 可选的请求头 }, onChange(info) { if (info.file.status !== 'uploading') { console.log(info.file, info.fileList); } if (info.file.status === 'done') { console.log(`${info.file.name} 上传成功`); } else if (info.file.status === 'error') { console.log(`${info.file.name} 上传失败`); } }, }; return ( <Upload {...props}> <Button icon={<UploadOutlined />}>上传文件</Button> </Upload> ); }; ``` ### 注意事项: - 确保后端接口 `/upload` 返回的 JSON 结构与 Ant Design Pro 的 `Upload` 组件兼容。 - 如果使用了跨域请求(CORS),需要在后端配置允许的来源、方法和头部信息。 - 文件存储路径应具有写权限,并且在生产环境中应考虑使用更安全的文件存储方式(如对象存储服务)。 ---
评论
成就一亿技术人!
拼手气红包6.0元
还能输入1000个字符
 
红包 添加红包
表情包 插入表情
 条评论被折叠 查看
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值