how to image upload on shopify app in backendside

I have code for Shopify backend side image upload. my code image uploads a successful message but when I go to backend side media file content then shows the error message “5 files failed”. I will share my code and my code is working but the image status shows uploading. That is not working in the processing and ready state. so please give proper solutions. I will share some screenshots.

import React, { useCallback, useEffect, useState, useRef } from "react";
import { json } from "@remix-run/node";
import { useActionData, useNavigation, useSubmit } from "@remix-run/react";
import {
  Page,
  Layout,
  Card,
  Button,
  BlockStack,
  Box,
  InlineStack,
  DropZone,
  LegacyStack,
  Thumbnail,
  Text,
} from "@shopify/polaris";
import { authenticate } from "../shopify.server";
import type { ActionFunctionArgs, LoaderFunctionArgs } from "@remix-run/node";

export const loader = async ({ request }: LoaderFunctionArgs) => {
  await authenticate.admin(request);

  return null;
};

export const action = async ({ request }: ActionFunctionArgs) => {
  const { admin } = await authenticate.admin(request);
  const color = ["Red", "Orange", "Yellow", "Green"][
    Math.floor(Math.random() * 4)
  ];
  const requestBody = await request.text();

  const formData = new URLSearchParams(requestBody);
  const name = formData.get("filename");
  const type = formData.get("filetype");
  const size = formData.get("filesize");
  const files = [
    {
      name: name,
      type: type,
      size: size,
    },
  ];
  const prepareFiles = (files: { name: string | null; type: string | null; size: string | null; }[]) =>
    files.map((file) => ({
        filename: file.name,
        mimeType: file.type,
        resource: file.type?.includes("image") ? "IMAGE" : "FILE",
        fileSize: file.size?.toString(),
        httpMethod: "POST",
    }));


  const preparedFiles = prepareFiles(files);

  const uploadFileResponse = await admin.graphql(
    `#graphql
    mutation stagedUploadsCreate($input: [StagedUploadInput!]!) {
      stagedUploadsCreate(input: $input) {
        stagedTargets {
          resourceUrl
          url
          parameters {
            name
            value
          }
        }
        userErrors {
          field
          message
        }
      }
    }
  `,
    { variables: { input: preparedFiles } },
  );

  const uplodeFileJson = await uploadFileResponse.json();

  const resourceurl = uplodeFileJson.data.stagedUploadsCreate.stagedTargets[0].resourceUrl;

    const fileCreateResponse = await admin.graphql(
        `#graphql
        mutation fileCreate($files: [FileCreateInput!]!) {
            fileCreate(files: $files) {
                files {
                    alt
                    createdAt
                    fileStatus
                    fileErrors {
                        code
                        details
                        message
                    }
                    
                    preview {
                        image {
                        url
                        }
                        status
                        __typename
                    }
                  ... on GenericFile {
                  id
                  }
                  ... on Video {
                  id
                  }
                }
                userErrors {
                    code
                    field
                    message
                }
            }
        }`,

        {
            variables: {
                files: {
                    alt: "Image",
                    contentType: "IMAGE",
                    originalSource: resourceurl,
                    
                },
            },
        },
    );

    const fileCreateJson = await fileCreateResponse.json();

    return ({
        stagedUpload: uplodeFileJson,
        fileCreate: fileCreateJson,
        resourceurl: resourceurl
    });

 
};

export default function Index() {
    const nav = useNavigation();
    const actionData = useActionData();
    const submit = useSubmit();
    const isLoading = ["loading", "submitting"].includes(nav.state) && nav.formMethod === "POST";


    useEffect(() => {
        if (actionData) {
        shopify.toast.show("Product created");
        }
    }, [actionData]);

    const [files, setFiles] = useState<File[]>([]);
    const inputRef = useRef<HTMLInputElement>(null);

    const handleDropZoneDrop = useCallback(
        async (dropFiles: File[], acceptedFiles: File[], rejectedFiles: File[]) => {
        if (acceptedFiles.length) {
            setFiles((prevFiles) => [...prevFiles, ...acceptedFiles]);
            for (const file of acceptedFiles) {
                console.log(file.name);
                console.log(file.size);
                console.log(file.type);
            }
        }
        },
        [],
    ); 
    const validImageTypes = ["image/gif", "image/jpeg", "image/png"];

    const fileUpload = !files.length && <DropZone.FileUpload />;
    const uploadedFiles = files.length > 0 && (
        <div style={{ padding: "0" }}>
        <LegacyStack vertical>
            {files.map((file, index) => (
            <LegacyStack alignment="center" key={index}>
                <Thumbnail
                size="small"
                alt={file.name}
                source={
                    validImageTypes.includes(file.type)
                    ? window.URL.createObjectURL(file)
                    : ""
                }
                />
                <div>
                {file.name}{" "}
                <Text variant="bodySm" as="p">
                    {file.size} bytes
                </Text>
                </div>
            </LegacyStack>
            ))}
        </LegacyStack>
        </div>
    );

    const generateProduct = () => {
        const filename = files[0]?.name;
        const filetype = files[0]?.type;
        const filesize = files[0]?.size;
        submit({ filename, filetype, filesize }, { replace: true, method: "POST" });
    };

  return (
    <Page>
      <BlockStack gap="500">
        <Layout>
          <Layout.Section>
            <Card>
              <InlineStack gap="300">
                <DropZone onDrop={handleDropZoneDrop}>
                  {uploadedFiles}
                  {fileUpload}
                </DropZone>
                <Button loading={isLoading} onClick={generateProduct}>
                  Generate a product
                </Button>
              </InlineStack>
            </Card>
          </Layout.Section>
        </Layout>
      </BlockStack>
    </Page>
  );
};

New contributor

mohit vamja is a new contributor to this site. Take care in asking for clarification, commenting, and answering.
Check out our Code of Conduct.

    const express = require('express');
const multer = require('multer'); // For handling file uploads
const Shopify = require('shopify-api-node'); // Shopify API client library

const app = express();
const upload = multer({ dest: 'uploads/' }); // Destination folder for uploaded files

// Initialize Shopify API client
const shopify = new Shopify({
  shopName: 'your-shop-name',
  apiKey: 'your-api-key',
  password: 'your-api-password',
});

// Route for handling image upload
app.post('/upload-image', upload.single('image'), (req, res) => {
  // Handle image processing, validation, etc.
  const imageFile = req.file; // The uploaded image file

  // Upload the image to Shopify
  shopify.asset.create({
    key: 'uploads/' + imageFile.filename, // File path on Shopify (you may need to adjust this)
    src: imageFile.path, // Local path of the uploaded image file
  })
  .then(asset => {
    // Image uploaded successfully
    res.json({ success: true, asset });
  })
  .catch(error => {
    // Error occurred during image upload
    console.error('Error uploading image to Shopify:', error);
    res.status(500).json({ success: false, error: 'Image upload failed' });
  });
});

// Start the server
app.listen(3000, () => {
  console.log('Server is running on port 3000');
});

Trang chủ Giới thiệu Sinh nhật bé trai Sinh nhật bé gái Tổ chức sự kiện Biểu diễn giải trí Dịch vụ khác Trang trí tiệc cưới Tổ chức khai trương Tư vấn dịch vụ Thư viện ảnh Tin tức - sự kiện Liên hệ Chú hề sinh nhật Trang trí YEAR END PARTY công ty Trang trí tất niên cuối năm Trang trí tất niên xu hướng mới nhất Trang trí sinh nhật bé trai Hải Đăng Trang trí sinh nhật bé Khánh Vân Trang trí sinh nhật Bích Ngân Trang trí sinh nhật bé Thanh Trang Thuê ông già Noel phát quà Biểu diễn xiếc khỉ Xiếc quay đĩa Dịch vụ tổ chức sự kiện 5 sao Thông tin về chúng tôi Dịch vụ sinh nhật bé trai Dịch vụ sinh nhật bé gái Sự kiện trọn gói Các tiết mục giải trí Dịch vụ bổ trợ Tiệc cưới sang trọng Dịch vụ khai trương Tư vấn tổ chức sự kiện Hình ảnh sự kiện Cập nhật tin tức Liên hệ ngay Thuê chú hề chuyên nghiệp Tiệc tất niên cho công ty Trang trí tiệc cuối năm Tiệc tất niên độc đáo Sinh nhật bé Hải Đăng Sinh nhật đáng yêu bé Khánh Vân Sinh nhật sang trọng Bích Ngân Tiệc sinh nhật bé Thanh Trang Dịch vụ ông già Noel Xiếc thú vui nhộn Biểu diễn xiếc quay đĩa Dịch vụ tổ chức tiệc uy tín Khám phá dịch vụ của chúng tôi Tiệc sinh nhật cho bé trai Trang trí tiệc cho bé gái Gói sự kiện chuyên nghiệp Chương trình giải trí hấp dẫn Dịch vụ hỗ trợ sự kiện Trang trí tiệc cưới đẹp Khởi đầu thành công với khai trương Chuyên gia tư vấn sự kiện Xem ảnh các sự kiện đẹp Tin mới về sự kiện Kết nối với đội ngũ chuyên gia Chú hề vui nhộn cho tiệc sinh nhật Ý tưởng tiệc cuối năm Tất niên độc đáo Trang trí tiệc hiện đại Tổ chức sinh nhật cho Hải Đăng Sinh nhật độc quyền Khánh Vân Phong cách tiệc Bích Ngân Trang trí tiệc bé Thanh Trang Thuê dịch vụ ông già Noel chuyên nghiệp Xem xiếc khỉ đặc sắc Xiếc quay đĩa thú vị
Trang chủ Giới thiệu Sinh nhật bé trai Sinh nhật bé gái Tổ chức sự kiện Biểu diễn giải trí Dịch vụ khác Trang trí tiệc cưới Tổ chức khai trương Tư vấn dịch vụ Thư viện ảnh Tin tức - sự kiện Liên hệ Chú hề sinh nhật Trang trí YEAR END PARTY công ty Trang trí tất niên cuối năm Trang trí tất niên xu hướng mới nhất Trang trí sinh nhật bé trai Hải Đăng Trang trí sinh nhật bé Khánh Vân Trang trí sinh nhật Bích Ngân Trang trí sinh nhật bé Thanh Trang Thuê ông già Noel phát quà Biểu diễn xiếc khỉ Xiếc quay đĩa
Thiết kế website Thiết kế website Thiết kế website Cách kháng tài khoản quảng cáo Mua bán Fanpage Facebook Dịch vụ SEO Tổ chức sinh nhật