有一些关于如何使用 Cloud Storage 上传文件的示例。这是example for Java,但也有其他语言(Python、Node、Go、Ruby 等)。
应用程序使用简单的表单让用户选择本地文件:
<!-- Rest of the code -->
<form method="POST" action="/upload" enctype="multipart/form-data">
<input type="file" name="file"> <input type="submit">
</form>
然后将表单发送到/upload servlet:
@Override
public void doPost(HttpServletRequest req, HttpServletResponse resp) throws IOException, ServletException {
final Part filePart = req.getPart("file");
final String fileName = filePart.getSubmittedFileName();
// Modify access list to allow all users with link to read file
List<Acl> acls = new ArrayList<>();
acls.add(Acl.of(Acl.User.ofAllUsers(), Acl.Role.READER));
// the inputstream is closed by default, so we don't need to close it here
Blob blob = storage.create(BlobInfo.newBuilder(BUCKET_NAME, fileName).setAcl(acls).build(),
filePart.getInputStream());
// return the public download link
resp.getWriter().print(blob.getMediaLink());
}
所有这些都发生在后端,因此用户不知道您使用什么服务来上传文件,这正是您想要的。
在这种特殊情况下,请确保避免使用以下线条:
resp.getWriter().print(blob.getMediaLink()); 写上传服务的地址:
https://www.googleapis.com/download/storage/v1/b/my-bucket-name/o/file-name.zip?generation=1524137198335299&alt=media
还有在前端,一行告诉用户:
<p>Select a file to upload to your Google Cloud Storage bucket.</p>