Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Add support to file upload #307

Closed
Jonatthu opened this issue Jan 17, 2020 · 6 comments
Closed

Add support to file upload #307

Jonatthu opened this issue Jan 17, 2020 · 6 comments
Labels
question Further information is requested

Comments

@Jonatthu
Copy link

Is this library helping out how to upload a file on a mutation?

If not how can be performed without any extra dependencies?

Or if we need dependencies...

How graphql-dotnet-server can be integrated with https://github.com/SimonCropp/GraphQL.Attachments?

@Jonatthu
Copy link
Author

I found the next snippet

            Field<StringGraphType>(
                "uploadFile",
                arguments: new QueryArguments(
                    new QueryArgument<StringGraphType> { Name = "args" },
                    new QueryArgument<FileGraphTpe> { Name = "file" }
                ),
                resolve: context => {
                    var files = context.UserContext.As<IFormFileCollection>();

                    SaveFIles(files);

                    return "Success";
                }
            );

But not sure if this is an official way to do it or graphql-dotnet-server can make it better or in a different way.

Reference:
graphql-dotnet/graphql-dotnet#419

@sungam3r
Copy link
Member

Relates to graphql-dotnet/graphql-dotnet#511

@sungam3r sungam3r added the question Further information is requested label Jan 17, 2020
@Jonatthu
Copy link
Author

@sungam3r Just found this https://github.com/JannikLassahn/graphql-dotnet-upload
Maybe can be integrated as part of this project

@Shane32
Copy link
Member

Shane32 commented Jul 12, 2022

The tests for GraphQL.NET Server v7 now includes a file-upload sample implementation along the lines written above, where it takes files passed via multipart/form-data and injects them as variables to the execution engine as a custom scalar graph type.

See: https://github.com/graphql-dotnet/server/blob/develop/tests/Transports.AspNetCore.Tests/Middleware/FileUploadTests.cs

This could of course be extended to support base64 string encoding as an alternative to multipart/form-data encoding, etc.

Please re-open if there are additional questions along these lines.

@Shane32 Shane32 closed this as completed Jul 12, 2022
@ng-druid
Copy link

I found this thread digging for info on how to read the file upload. We have successfully been able to upload a file using graph QL. Now just need to figure out how to download it using the same api. The Text property is always empty when querying. Anyway… here is how to upload with go.

(origionally built for s3)

func UploadMediaFile(req *events.APIGatewayProxyRequest, ac *ActionContext) (events.APIGatewayProxyResponse, error) {

	res := events.APIGatewayProxyResponse{StatusCode: 403}

	body, err := base64.StdEncoding.DecodeString(req.Body)
	if err != nil {
		return res, err
	}

	r := http.Request{
		Method: req.HTTPMethod,
		Header: map[string][]string{
			"Content-Type": {req.Headers["Content-Type"]},
		},
		Body: ioutil.NopCloser(bytes.NewBuffer(body)),
	}

	file, header, err := r.FormFile("File")
	defer file.Close()
	if err != nil {
		return res, err
	}

	contentType := header.Header.Get("Content-Type")
	ext, _ := mime.ExtensionsByType(contentType)
	id := header.Filename
	if pos := strings.LastIndexByte(header.Filename, '.'); pos != -1 {
		id = header.Filename[:pos]
	}

	if contentType == "text/markdown" {
		ext = []string{".md"}
	}

	// Necessary to commit to github but not for s3
	dataBuffer := bytes.NewBuffer(nil)
	if _, err := io.Copy(dataBuffer, file); err != nil {
		return res, err
	}

	d := []byte(dataBuffer.String())
	suffix := ""
	if os.Getenv("GITHUB_BRANCH") == "master" {
		suffix = "-prod"
	}
	params := repo.CommitParams{
		Repo:   "rollthecloudinc/" + req.PathParameters["site"] + "-objects" + suffix,
		Branch: os.Getenv("GITHUB_BRANCH"),
		Path:   "media/" + id + ext[0],
		Data:   &d,
	}

	repo.Commit(
		ac.GithubV4Client,
		&params,
	)

	/*userId := GetUserId(req)
	uploader := s3manager.NewUploader(ac.Session)
	_, err = uploader.Upload(&s3manager.UploadInput{
		Bucket:      aws.String(ac.BucketName),
		Key:         aws.String(data["path"]),
		Body:        file,
		ContentType: aws.String(data["contentType"]),
		Metadata:    map[string]*string{"userId": &userId},
	})
	if err != nil {
		return res, err
	}*/

	data := map[string]string{
		"id":                 id,
		"path":               "media/" + id + ext[0],
		"contentType":        contentType,
		"contentDisposition": header.Header.Get("Content-Disposition"),
		"length":             fmt.Sprint(header.Size),
	}

	res.StatusCode = 200
	res.Headers = map[string]string{
		"Content-Type": "application/json",
	}

	body, err = json.Marshal(data)
	res.Body = string(body)

	return res, nil
}

Full code: https://github.com/rollthecloudinc/verti-go/blob/master/api/media/main.go

@Shane32
Copy link
Member

Shane32 commented Aug 20, 2022

@ng-druid Thanks! I’ve added a link to this thread in the readme.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
question Further information is requested
Projects
None yet
Development

No branches or pull requests

4 participants