谷歌云存储使用java上传文件

我正在使用 Java servlet 和 JSP 创建一个 Web 应用程序,我想在 JSP 中创建一个上传表单,以便我的客户能够上传和下载内容。我正在使用 Cloud Storage 和我的默认存储桶来上传内容。我遵循了谷歌关于读写谷歌云存储的教程。


这是我的 Servlet:


public class Create extends HttpServlet {


    public static final boolean SERVE_USING_BLOBSTORE_API = false;


    private final GcsService gcsService = GcsServiceFactory.createGcsService(new RetryParams.Builder()

            .initialRetryDelayMillis(10)

            .retryMaxAttempts(10)

            .totalRetryPeriodMillis(15000)

            .build());


    @Override

    public void doGet(HttpServletRequest req, HttpServletResponse resp) throws IOException {

        GcsFilename fileName = getFileName(req);

        if (SERVE_USING_BLOBSTORE_API) {

            BlobstoreService blobstoreService =  BlobstoreServiceFactory.getBlobstoreService();

            BlobKey blobKey = blobstoreService.createGsBlobKey(

                    "/gs/" + fileName.getBucketName() + "/" + fileName.getObjectName());

            blobstoreService.serve(blobKey, resp);

        } else {

            GcsInputChannel readChannel = gcsService.openPrefetchingReadChannel(fileName, 0, BUFFER_SIZE);

            copy(Channels.newInputStream(readChannel), resp.getOutputStream());

        }

    }


我可以成功上传和下载,但只能是文本,而不是图像、pdf 等真实文件,这是我的问题。本教程用于阅读和编写文本,但我想上传真实文件。正如您从我的 jsp 中看到的,enctype 是"text/plain":


<form action="/index.html" enctype="text/plain" method="get" name="putFile" id="putFile">

      <div>

        Bucket: <input type="text" name="bucket" />

        File Name: <input type="text" name="fileName" />

        <br /> File Contents: <br />

        <textarea name="content" id="content" rows="3" cols="60"></textarea>

        <br />

        <input type="submit" onclick='uploadFile(this)' value="Upload Content" />

      </div>

    </form>

我试图将其更改为“multipart/form-data”并放置一个


<input name="content" id="content" type="file">

但这不会上传真实文件,只会上传文件的假路径。我想知道如何上传真实文件,任何帮助将不胜感激。


蝴蝶不菲
浏览 225回答 2
2回答

潇潇雨雨

我找到了解决办法。这是我的 JSP:<form action="/create" enctype="multipart/form-data" method="post" name="putFile" id="putFile">&nbsp; &nbsp; &nbsp; <div>&nbsp; &nbsp; &nbsp; &nbsp; File Name: <input type="text" name="fileName" />&nbsp; &nbsp; &nbsp; &nbsp; <br /> File Contents: <br />&nbsp; &nbsp; &nbsp; &nbsp; <input type="submit" value="Upload Content" />&nbsp; &nbsp; &nbsp; </div></form>当我提交表单时,它会进入这个 Servlet:@Overridepublic void doPost(HttpServletRequest req, HttpServletResponse resp) throws IOException {&nbsp; &nbsp; Part filePart = req.getPart("content"); /*Get file from jsp*/&nbsp; &nbsp; /*Get file name of file from jsp*/&nbsp; &nbsp; String name = Paths.get(filePart.getSubmittedFileName()).getFileName().toString();&nbsp; &nbsp; GcsFileOptions instance = GcsFileOptions.getDefaultInstance();&nbsp; &nbsp; GcsFilename fileName = new GcsFilename(BUCKET_NAME, name);&nbsp; &nbsp; GcsOutputChannel outputChannel;&nbsp; &nbsp; outputChannel = gcsService.createOrReplace(fileName, instance);&nbsp; &nbsp; /*Pass the file to copy function, wich uploads the file to cloud*/&nbsp; &nbsp; copy(filePart.getInputStream(), Channels.newOutputStream(outputChannel));&nbsp; &nbsp; req.getRequestDispatcher("download.jsp").forward(req, resp);}private GcsFilename getFileName(HttpServletRequest req) {&nbsp; &nbsp; String[] splits = req.getRequestURI().split("/", 4);&nbsp; &nbsp; if (!splits[0].equals("") || !splits[1].equals("gcs")) {&nbsp; &nbsp; &nbsp; &nbsp; throw new IllegalArgumentException("The URL is not formed as expected. " +&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; "Expecting /gcs/<bucket>/<object>");&nbsp; &nbsp; }&nbsp; &nbsp; return new GcsFilename(splits[2], splits[3]);}private void copy(InputStream input, OutputStream output) throws IOException {&nbsp; &nbsp; try {&nbsp; &nbsp; &nbsp; &nbsp; byte[] buffer = new byte[BUFFER_SIZE];&nbsp; &nbsp; &nbsp; &nbsp; int bytesRead = input.read(buffer);&nbsp; &nbsp; &nbsp; &nbsp; while (bytesRead != -1) {&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; output.write(buffer, 0, bytesRead);&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; bytesRead = input.read(buffer);&nbsp; &nbsp; &nbsp; &nbsp; }&nbsp; &nbsp; } finally {&nbsp; &nbsp; &nbsp; &nbsp; input.close();&nbsp; &nbsp; &nbsp; &nbsp; output.close();&nbsp; &nbsp; }}

偶然的你

下面是一个关于如何将 blob 上传到 Cloud Storage 的示例:首先,您使用以下几行初始化存储:private static Storage storage = null;&nbsp; // [START init]&nbsp; static {&nbsp; &nbsp; storage = StorageOptions.getDefaultInstance().getService();&nbsp; }&nbsp; // [END init]您可以getImageUrl在行中的方法上根据您的需要更改代码以接受不同的文件扩展名String[] allowedExt = {"jpg", "jpeg", "png", "gif"};/**&nbsp;* Extracts the file payload from an HttpServletRequest, checks that the file extension&nbsp;* is supported and uploads the file to Google Cloud Storage.&nbsp;*/public String getImageUrl(HttpServletRequest req, HttpServletResponse resp,&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; final String bucket) throws IOException, ServletException {&nbsp; Part filePart = req.getPart("file");&nbsp; final String fileName = filePart.getSubmittedFileName();&nbsp; String imageUrl = req.getParameter("imageUrl");&nbsp; // Check extension of file&nbsp; if (fileName != null && !fileName.isEmpty() && fileName.contains(".")) {&nbsp; &nbsp; final String extension = fileName.substring(fileName.lastIndexOf('.') + 1);&nbsp; &nbsp; String[] allowedExt = {"jpg", "jpeg", "png", "gif"};&nbsp; &nbsp; for (String s : allowedExt) {&nbsp; &nbsp; &nbsp; if (extension.equals(s)) {&nbsp; &nbsp; &nbsp; &nbsp; return this.uploadFile(filePart, bucket);&nbsp; &nbsp; &nbsp; }&nbsp; &nbsp; }&nbsp; &nbsp; throw new ServletException("file must be an image");&nbsp; }&nbsp; return imageUrl;}这里在文件名中附加了时间戳,如果您想让文件名唯一,这可能是一个好主意。/**&nbsp;* Uploads a file to Google Cloud Storage to the bucket specified in the BUCKET_NAME&nbsp;* environment variable, appending a timestamp to end of the uploaded filename.&nbsp;*/@SuppressWarnings("deprecation")public String uploadFile(Part filePart, final String bucketName) throws IOException {&nbsp; DateTimeFormatter dtf = DateTimeFormat.forPattern("-YYYY-MM-dd-HHmmssSSS");&nbsp; DateTime dt = DateTime.now(DateTimeZone.UTC);&nbsp; String dtString = dt.toString(dtf);&nbsp; final String fileName = filePart.getSubmittedFileName() + dtString;&nbsp; // the inputstream is closed by default, so we don't need to close it here&nbsp; BlobInfo blobInfo =&nbsp; &nbsp; &nbsp; storage.create(&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; BlobInfo&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; .newBuilder(bucketName, fileName)&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; // Modify access list to allow all users with link to read file&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; .setAcl(new ArrayList<>(Arrays.asList(Acl.of(User.ofAllUsers(), Role.READER))))&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; .build(),&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; filePart.getInputStream());&nbsp; // return the public download link&nbsp; return blobInfo.getMediaLink();}在本文档中,您将找到更多详细信息:https : //cloud.google.com/java/getting-started/using-cloud-storage#uploading_blobs_to_cloud_storage此示例的完整代码在 github 中:https : //github.com/GoogleCloudPlatform/getting-started-java/blob/master/bookshelf/3-binary-data/src/main/java/com/example/getstarted/ util/CloudStorageHelper.java
打开App,查看更多内容
随时随地看视频慕课网APP

相关分类

Java