问题描述
我正在使用我的upload.java servlet将.jpg存储到GCS。
我使用GCS客户端库而不是Google Cloud Storage API。但我没有找到任何样品上传照片(doPost方法),所以我的代码无法正常工作......
发送成功(我可以看到我的照片在GCS上的尺寸为465.24KB),但是当我尝试查看这一个时,我不能:
upload.java servlet
public void doPost(HttpServletRequest请求,HttpServletResponse响应)
抛出IOException异常{
//从输入流读取文件内容
GcsService gcsService = GcsServiceFactory.createGcsService();
GcsFilename filename = new GcsFilename(BUCKETNAME,FILENAME);
GcsFileOptions options = new GcsFileOptions.Builder()
.mimeType(image / jpeg)
.acl(public-read)
.addUserMetadata(myfield1,我的字段值)
.build();
GcsOutputChannel writeChannel = gcsService.createOrReplace(filename,options);
InputStream is = request.getInputStream();
尝试{
copy(is,Channels.newOutputStream(writeChannel));
} finally {
writeChannel.close();
is.close();
$ b private void copy(InputStream input,OutputStream output)throws IOException {
byte [] buffer = new byte [256];
int bytesRead = input.read(buffer);
while(bytesRead!= -1){
output.write(buffer,0,bytesRead);
bytesRead = input.read(buffer);
$
android代码(发送照片)
HttpPost httppost = new HttpPost(adress.appengine.com/upload);
//在文件上保存文件qui contient la photo que l'on vient de prendre(可通过儿子路径访问)
文件f =新文件(AccueilActivity.fileUri。的getPath());
//关于FileBody(Contenu de notrerequêtehttp POST)contenant notre photo
FileBody fileBody = new FileBody(f);
// Permet decréerunerequêteavec plusieurs partie
MultipartEntity reqEntity = new MultipartEntity();
//关于照片avec le motclé文件。
reqEntity.addPart(file,fileBody);
//设置为notrerequêteHTTP
httppost.setEntity(reqEntity);
//执行NOT POST请求HTTP Post,et appele du coup automatiquement le servlet上传,
//等会议响应。
HttpResponse response = httpClient.execute(httppost);
$ b $ // //使用HTTP协议(Tout sauf le coderéponse)
HttpEntity urlEntity = response.getEntity();
提前致谢! 解决方案
我终于找到(并且由我自己)解决我的问题!我为此感到自豪= D
Android的代码:
//动作àréaliseren fond
保护字符串doInBackground(String ... params){
//不需要的HTTP
HttpClient httpClient = new DefaultHttpClient();
//关于构造notre adresse Postgrâceàce que l'on vient derécupérer
HttpPost httppost = new HttpPost(http://your_id.appspot.com/upload);
//在文件上保存文件qui contient la photo que l'on vient de prendre(
File f = new File(AccueilActivity.fileUri.getPath()) ;
// Etlàon essaie!
尝试{
MultipartEntityBuilder entityBuilder = MultipartEntityBuilder.create();
entityBuilder.setMode(HttpMultipartMode.BROWSER_COMPATIBLE);
entityBuilder.addBinaryBody(Photo_a_uploader,f);
entityBuilder.addTextBody(Type,Type que l'utilisateur a choisi);
httppost.setEntity(entityBuilder.build());
HttpResponse response = httpClient.execute(httppost);
$ b} catch(ClientProtocolException e){
//在tombe dans le catch上,设置notre变量à2.
e.printStackTrace();
} catch(IOException e){
//在tombe dans le catch上,设置notre变量à2.
e.printStackTrace();
}
代码App Engine
@Override
public void doPost(HttpServletRequest req,HttpServletResponse res)
throws ServletException,IOException {
//从输入流中读取文件内容
GcsService gcsService = GcsServiceFactory.createGcsService();
GcsFilename filename = new GcsFilename(BUCKETNAME,FILENAME);
GcsFileOptions options = new GcsFileOptions.Builder()
.mimeType(image / jpg)
.acl(public-read)
.addUserMetadata myfield1,我的字段值)
.build();
GcsOutputChannel writeChannel = gcsService.createOrReplace(filename,options);
ServletFileUpload upload = new ServletFileUpload();
res.setContentType(text / plain);
尝试{
FileItemIterator iterator = upload.getItemIterator(req);
while(iterator.hasNext()){
FileItemStream item = iterator.next();
InputStream stream = item.openStream(); $ item.isFormField()){
log.warning(Champs texte avec id:+ item.getFieldName()+,et nom:+ Streams.asString()流));
} else {
log.warning(Nous avons un fichieràuploader:+ item.getFieldName()+
,appelé=+ item.getName());
//你现在有文件名(item.getName()和
//内容(你可以从流中读取),这里我们只是
//打印它们退出到servlet输出流,但是你
//可能会想要做一些更有趣的事情(对于
//例如,将它们包装在Blob中并将它们提交给
//数据存储)
//打开一个通道写入它
byte [] bytes = ByteStreams.toByteArray(stream);
try {
writeChannel.write(ByteBuffer.wrap(bytes));
} finally {
writeChannel.close();
stream.close();
}
}
} catch(FileUploadException e){
// TODO自动生成的catch块
e.printStackTrace();
}
}
我希望这些示例可以帮助您使用应用引擎和Google云存储!
I'm working on my upload.java servlet to store .jpg to GCS.
I use GCS client library instead of Google Cloud Storage API. But I dont't find any sample to upload photo (doPost Method) so my code doesn't work...
Sending is a success (I can see my photo on GCS with a good size 465.24KB), but when I try to view this one, i can't:
Here is my code:
upload.java servlet public void doPost(HttpServletRequest request, HttpServletResponse response) throws IOException {
//Read the file contents from the input stream
GcsService gcsService = GcsServiceFactory.createGcsService();
GcsFilename filename = new GcsFilename(BUCKETNAME, FILENAME);
GcsFileOptions options = new GcsFileOptions.Builder()
.mimeType("image/jpeg")
.acl("public-read")
.addUserMetadata("myfield1", "my field value")
.build();
GcsOutputChannel writeChannel = gcsService.createOrReplace(filename, options);
InputStream is = request.getInputStream();
try {
copy(is, Channels.newOutputStream(writeChannel));
} finally {
writeChannel.close();
is.close();
}
}
private void copy(InputStream input, OutputStream output) throws IOException {
byte[] buffer = new byte[256];
int bytesRead = input.read(buffer);
while (bytesRead != -1) {
output.write(buffer, 0, bytesRead);
bytesRead = input.read(buffer);
}
}
android code (To send photo)
HttpPost httppost = new HttpPost("adress.appengine.com/upload");
//On créé un fichier File qui contient la photo que l'on vient de prendre (Accessible via son Path)
File f = new File(AccueilActivity.fileUri.getPath());
//On créé un FileBody (Contenu de notre requête http POST) contenant notre photo
FileBody fileBody = new FileBody(f);
//Permet de créer une requête avec plusieurs partie
MultipartEntity reqEntity = new MultipartEntity();
//On ajoute notre photo avec le mot clé file.
reqEntity.addPart("file", fileBody);
//On set notre requête HTTP
httppost.setEntity(reqEntity);
//On execute notre requete HTTP Post, et on appele du coup automatiquement le servlet "uploaded",
//et on met la réponse dans response.
HttpResponse response = httpClient.execute(httppost);
//Ici on récupère l'entête de notre réponse HTTP (Tout sauf le code réponse)
HttpEntity urlEntity = response.getEntity();
Thanks in advance !
I finally found (And by myself) the solution to my problem! And I pretty proud of that =D
The code for Android:
//Actions à réaliser en fond
protected String doInBackground(String... params) {
//Création d'une requête HTTP
HttpClient httpClient = new DefaultHttpClient();
//On construit notre adresse Post grâce à ce que l'on vient de récupérer
HttpPost httppost = new HttpPost("http://your_id.appspot.com/upload");
//On créé un fichier File qui contient la photo que l'on vient de prendre (Accessible via son Path)
File f = new File(AccueilActivity.fileUri.getPath());
//Et là on essaie !
try {
MultipartEntityBuilder entityBuilder = MultipartEntityBuilder.create();
entityBuilder.setMode(HttpMultipartMode.BROWSER_COMPATIBLE);
entityBuilder.addBinaryBody("Photo_a_uploader", f);
entityBuilder.addTextBody("Type", "Type que l'utilisateur a choisi");
httppost.setEntity(entityBuilder.build());
HttpResponse response = httpClient.execute(httppost);
} catch (ClientProtocolException e) {
// Si on tombe dans le catch, on set notre variable à 2.
e.printStackTrace();
} catch (IOException e) {
// Si on tombe dans le catch, on set notre variable à 2.
e.printStackTrace();
}
The code App Engine
@Override
public void doPost(HttpServletRequest req, HttpServletResponse res)
throws ServletException, IOException {
//Read the file contents from the input stream
GcsService gcsService = GcsServiceFactory.createGcsService();
GcsFilename filename = new GcsFilename(BUCKETNAME, FILENAME);
GcsFileOptions options = new GcsFileOptions.Builder()
.mimeType("image/jpg")
.acl("public-read")
.addUserMetadata("myfield1", "my field value")
.build();
GcsOutputChannel writeChannel = gcsService.createOrReplace(filename, options);
ServletFileUpload upload = new ServletFileUpload();
res.setContentType("text/plain");
try {
FileItemIterator iterator = upload.getItemIterator(req);
while (iterator.hasNext()) {
FileItemStream item = iterator.next();
InputStream stream = item.openStream();
if (item.isFormField()) {
log.warning("Champs texte avec id: " + item.getFieldName()+", et nom: "+Streams.asString(stream));
} else {
log.warning("Nous avons un fichier à uploader : " + item.getFieldName() +
", appelé = " + item.getName());
// You now have the filename (item.getName() and the
// contents (which you can read from stream). Here we just
// print them back out to the servlet output stream, but you
// will probably want to do something more interesting (for
// example, wrap them in a Blob and commit them to the
// datastore).
// Open a channel to write to it
byte[] bytes = ByteStreams.toByteArray(stream);
try {
writeChannel.write(ByteBuffer.wrap(bytes));
} finally {
writeChannel.close();
stream.close();
}
}
}
} catch (FileUploadException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
I hope these sample help you with app engine and google cloud storage !
这篇关于照片无法正确上传GCS App Engine的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!