0
0

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

file取り扱い

Last updated at Posted at 2025-04-21
import com.google.cloud.functions.HttpFunction;
import com.google.cloud.functions.HttpRequest;
import com.google.cloud.functions.HttpResponse;

import org.apache.commons.fileupload.FileItem;
import org.apache.commons.fileupload.disk.DiskFileItemFactory;
import org.apache.commons.fileupload.servlet.ServletFileUpload;
import org.apache.commons.fileupload.FileUploadException;

import java.io.*;
import java.util.List;

public class FileUploadFunction implements HttpFunction {

    @Override
    public void service(HttpRequest request, HttpResponse response) throws Exception {
        if (!ServletFileUpload.isMultipartContent(new HttpRequestWrapper(request))) {
            response.setStatusCode(400);
            response.getWriter().write("Content-Type is not multipart/form-data");
            return;
        }

        DiskFileItemFactory factory = new DiskFileItemFactory();
        ServletFileUpload upload = new ServletFileUpload(factory);

        List<FileItem> items;
        try {
            items = upload.parseRequest(new HttpRequestWrapper(request));
        } catch (FileUploadException e) {
            response.setStatusCode(500);
            response.getWriter().write("Failed to parse multipart request");
            return;
        }

        for (FileItem item : items) {
            if (!item.isFormField() && "file".equals(item.getFieldName())) {
                String fileName = item.getName();
                byte[] fileBytes = item.get();

                // ByteArrayInputStream を使って再利用可能に
                ByteArrayInputStream reusableStream = new ByteArrayInputStream(fileBytes);

                // 内容を読み込んで表示(例)
                try (BufferedReader reader = new BufferedReader(new InputStreamReader(reusableStream))) {
                    String line;
                    while ((line = reader.readLine()) != null) {
                        System.out.println("Line: " + line);
                    }
                }

                response.getWriter().write("File received: " + fileName + "\n");
                return;
            }
        }

        response.setStatusCode(400);
        response.getWriter().write("No file part found");
    }
}

0
0
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
0
0

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?