这是我在服务器端的上传功能:
private static final int BUFFER_SIZE = 2 * 1024 * 1024;
public void processRequest(HttpServletRequest request)
throws ServletException, IOException {
// multipart request
final Part filePart = request.getPart("file");
// some function to get the filename from part
final String name = getFileName(filePart);
// some function to convert the filename to GcsFilename
final GcsFilename fileName = getFileNameGCS(name);
//method to copy file taken from official documentation
GcsFileOptions instance = GcsFileOptions.getDefaultInstance();
GcsOutputChannel outputChannel = gcsService.createOrReplace(fileName, instance);
copy(filePart.getInputStream(), Channels.newOutputStream(outputChannel));
}
private void copy(InputStream input, OutputStream output) throws IOException {
try {
byte[] buffer = new byte[BUFFER_SIZE];
int bytesRead = input.read(buffer);
while (bytesRead != -1) {
output.write(buffer, 0, bytesRead);
bytesRead = input.read(buffer);
}
} finally {
input.close();
output.close();
}
}
这是我在客户端(Angular2)album.component.ts上的帖子功能:
uploadAlbum(index:number){
const formData = new FormData();
formData.append('file', this.targets[index].file, '/gcs/my-bucket/' + index +'/cover/cover.jpg');
this.http.post('/api/photos',formData, {responseType: 'text'}).subscribe(
(data: any) => {
console.log(data)
},
err => {
console.log(err)
}
);
}
现在,我使用此方法来检索本地文件的公共网址(App Engine Google Cloud Storage模拟服务器上传并将其放置在本地空间中)
示例代码:
...
BlobKey blobKey = blobStore.createGsBlobKey("/gs/" + bucket + "/" + listFilenames.get(i));
log.info("/gs/" + bucket + "/" + listFilenames.get(i));
ImagesService imagesService = ImagesServiceFactory.getImagesService();
String url = imagesService.getServingUrl(ServingUrlOptions.Builder.withBlobKey(blobKey));
jsonObj.put("path", url);
json.put(jsonObj);
...
基本上,我在该函数另一部分所做的工作是分析所有文件并过滤出我感兴趣的文件。
它可以用encoded_gs_key
获取URL,但是什么也没显示。
我的上传有问题吗?即使在指定位置找不到文件,BlobStore也会提供链接吗?
还有一件事是,即使我的文件夹和图像不同(encoded_gs_key
,例如0/cover/cover.jpg
,所以根文件夹,图像和文件名相同),我总是得到相同的1/cover/cover.jpg
链接< / p>
答案 0 :(得分:1)
现在我明白发生了什么。我有一个连接过滤器,该过滤器仅使我可以通过以下路径/api*
删除,并且看起来工作得更好:
原始的connexionFilter类:
public class connexionFilter implements Filter {
@Override
public void init(FilterConfig filterConfig) throws ServletException {
// TODO Auto-generated method stub
}
@Override
public void doFilter(ServletRequest request, ServletResponse response, FilterChain chain)
throws IOException, ServletException {
HttpServletRequest req = (HttpServletRequest) request;
HttpServletResponse resp = (HttpServletResponse) response;
String path = ((HttpServletRequest) request).getRequestURI();
if(path.startsWith("/api"))
{
chain.doFilter(req, resp);
}
}
@Override
public void destroy() {
// TODO Auto-generated method stub
}
}