通过android向GAE上传文件

通过android向GAE上传文件,android,google-app-engine,Android,Google App Engine,我在谷歌应用引擎上工作了三天,终于遇到了这个我无法解决的问题。我做了很多研究,但能找到任何令人信服的东西。M 在设置了我的Google app Engine帐户后,当我调用我的应用程序url“my-app-id.appspot.com/myservlet”时,GAE上的简单Servlet就能够在我的Google bucket中写入.txt文件。相同的代码段如下所示: fetchurl.java DefaultHttpClient hc=new DefaultHtt

我在谷歌应用引擎上工作了三天,终于遇到了这个我无法解决的问题。我做了很多研究,但能找到任何令人信服的东西。M

在设置了我的Google app Engine帐户后,当我调用我的应用程序url“my-app-id.appspot.com/myservlet”时,GAE上的简单Servlet就能够在我的Google bucket中写入.txt文件。相同的代码段如下所示:

 fetchurl.java 

             DefaultHttpClient hc=new DefaultHttpClient();
             ResponseHandler <String> res=new BasicResponseHandler();
             HttpGet postMethod=new HttpGet("http://my-app-id.appspot.com/uploadservlet");

             String response=hc.execute(postMethod,res);
现在我的问题是,当我使用multi-part通过POST方法发送一些文件时,Servlet@app引擎不工作,我在eclipse中收到错误消息“Filenotfound”

Android端的.java文件

  urlString = "http://my-app-id.appspot.com/uploadservlet";
  URL url = new URL(urlString);

             // Open a HTTP connection to the URL
             conn = (HttpURLConnection) url.openConnection();
             conn.setConnectTimeout(90000);

             // Allow Inputs
             conn.setDoInput(true);

             // Allow Outputs
             conn.setDoOutput(true);

             // Don't use a cached copy.
             conn.setUseCaches(false);

             // Use a post method.
             conn.setRequestMethod("POST");

             isOK = true;

             conn.setRequestProperty("Connection", "Keep-Alive");

             conn.setRequestProperty("Content-Type",
                     "multipart/form-data;boundary=" + boundary);

             DataOutputStream dos = new DataOutputStream(conn.getOutputStream());


            dos.writeBytes(twoHyphens + boundary + lineEnd);
            dos.writeBytes("Content-Disposition: form-data; name=param1;filename="
                            + param1 + "" + lineEnd);
            dos.writeBytes(lineEnd);
            dos.writeBytes(twoHyphens + boundary + lineEnd);
            Log.e(Tag, "Param1 are written");

            dos.writeBytes(twoHyphens + boundary + lineEnd);
            dos.writeBytes("Content-Disposition: form-data; name=param2;filename="
                            + param2 + "" + lineEnd);
            dos.writeBytes(lineEnd);
            dos.writeBytes(twoHyphens + boundary + lineEnd);
            Log.e(Tag, "Param2 are written");



            FileInputStream fileInputStream = new FileInputStream(new File(
                    path));
            dos.writeBytes(twoHyphens + boundary + lineEnd);
            dos.writeBytes("Content-Disposition: form-data; name=uploadedfile;filename="
                         + path + "" + lineEnd);
            dos.writeBytes(lineEnd);

            Log.e(Tag, "Headers are written");

             // create a buffer of maximum size

             int bytesAvailable = fileInputStream.available();
             int maxBufferSize = 1000;
             // int bufferSize = Math.min(bytesAvailable, maxBufferSize);
             byte[] buffer = new byte[bytesAvailable];

             // read file and write it into form...

             int bytesRead = fileInputStream.read(buffer, 0, bytesAvailable);

             while (bytesRead > 0) 
             {
                 dos.write(buffer, 0, bytesAvailable);
                 bytesAvailable = fileInputStream.available();
                 bytesAvailable = Math.min(bytesAvailable, maxBufferSize);
                 bytesRead = fileInputStream.read(buffer, 0, bytesAvailable);
             }

             // send multipart form data necesssary after file data...
             //dos.writeBytes(lineEnd);
             dos.writeBytes(twoHyphens + boundary + lineEnd);
             dos.writeBytes(lineEnd);
             dos.writeBytes(twoHyphens + boundary + twoHyphens + lineEnd);
我想知道这种方法是否正确。如果不是,还有什么解决方案…我也看了blobstorage,但它也做了同样的事情,将文件写入bucket而不是上传…请帮助我,伙计们…任何事情都将是伟大和感激的

 Servlet code to handle file upload and save to Google storage--

 @MultipartConfig   
 @SuppressWarnings("serial")
   public class SecondtrygoogleServlet extends HttpServlet 
   {
public static String BUCKETNAME = "androidbucket";
public static String FILENAME = "shikhatry.txt";

private static final long serialVersionUID = 1L;


private static final int THRESHOLD_SIZE = 1024 * 1024 * 3; // 3MB
private static final int MAX_FILE_SIZE = 1024 * 1024 * 40; // 40MB
private static final int REQUEST_SIZE = 1024 * 1024 * 50; // 50MB



public void doPost(HttpServletRequest request, HttpServletResponse response)
        throws ServletException, IOException 
{
    // checks if the request actually contains upload file
    if (!ServletFileUpload.isMultipartContent(request)) {
        // if not, we stop here
        return;
    }

    response.setContentType("text/plain");
    response.getWriter().println("Hello, test1 world");

    // configures some settings
    DiskFileItemFactory factory = new DiskFileItemFactory();
    factory.setSizeThreshold(THRESHOLD_SIZE);
    factory.setRepository(new File(System.getProperty("java.io.tmpdir")));

    ServletFileUpload upload = new ServletFileUpload(factory);
    upload.setFileSizeMax(MAX_FILE_SIZE);
    upload.setSizeMax(REQUEST_SIZE);
    java.io.PrintWriter out = response.getWriter( );

    try {
            // parses the request's content to extract file data
            List<?> formItems = upload.parseRequest(request);
            out.println("Number of fields: " + formItems.size());
            Iterator<?> iter = formItems.iterator();


            // iterates over form's fields
            while (iter.hasNext()) 
            {
                out.println("Inside while loop");
                FileItem item = (FileItem) iter.next();
                // processes only fields that are not form fields
                if (!item.isFormField()) 
                {

                    String temp = item.getFieldName();
                    out.println("Parameter Name"+temp);

                    if(temp.equals("uploadedfile"))
                    {
                        String fileName = new File(item.getName()).getName();
                        FILENAME = fileName+".txt";
                        out.println("Filename"+fileName);


                        FileService fileService = FileServiceFactory.getFileService();
                        GSFileOptionsBuilder optionsBuilder = new GSFileOptionsBuilder()
                        .setBucket(BUCKETNAME)
                        .setKey(FILENAME)
                        .setMimeType("text/html") //audio/mp3 text/html
                        .setAcl("public_read")
                        .addUserMetadata("myfield1", "my field value");


                     AppEngineFile writableFile =
                         fileService.createNewGSFile(optionsBuilder.build());

                     // Open a channel to write to it
                     boolean lock = false;
                     FileWriteChannel writeChannel =
                         fileService.openWriteChannel(writableFile, lock);


                     // Different standard Java ways of writing to the channel
                     // are possible. Here we use a PrintWriter:

                     InputStream inputStream = item.getInputStream();
                     int readBytes = 0;
                     byte[] buffer = new byte[10000];



                     while ((readBytes = inputStream.read(buffer, 0, 10000)) != -1) 
                     {
                        writeChannel.write(ByteBuffer.wrap(buffer));

                     }

                     inputStream.close();

                     writeChannel.closeFinally();
                     response.getWriter().println("Done writing...");

                }
                else if(temp.equals("param1"))
                {
                    out.println("Inside param1");
                    //String param1Val = new File(item.getName()).getName();                        
                    //BUCKETNAME = param1Val;
                }
                else if(temp.equals("param2"))
                {
                    out.println("Inside param2");
                    //String param2Val = new File(item.getName()).getName();

                    //BUCKETNAME = param2Val;


                }
            }
        }
        request.setAttribute("message", "Upload has been done successfully!");
    } catch (Exception ex) {
        request.setAttribute("message", "There was an error: " + ex.getMessage());
    }


}
Servlet处理文件上传和保存到Google存储的代码--
@多重配置
@抑制警告(“串行”)
公共类SecondtrygoogleServlet扩展了HttpServlet
{
公共静态字符串BUCKETNAME=“androidbucket”;
公共静态字符串FILENAME=“shikhatry.txt”;
私有静态最终长serialVersionUID=1L;
私有静态最终整数阈值\u SIZE=1024*1024*3;//3MB
私有静态最终int MAX_FILE_SIZE=1024*1024*40;//40MB
私有静态最终整数请求_SIZE=1024*1024*50;//50MB
public void doPost(HttpServletRequest请求、HttpServletResponse响应)
抛出ServletException、IOException
{
//检查请求是否确实包含上载文件
如果(!ServletFileUpload.isMultipartContent(请求)){
//如果不是,我们就到此为止
返回;
}
response.setContentType(“文本/普通”);
response.getWriter().println(“您好,test1 world”);
//配置一些设置
DiskFileItemFactory=新的DiskFileItemFactory();
factory.setSizeThreshold(阈值大小);
setRepository(新文件(System.getProperty(“java.io.tmpdir”));
ServletFileUpload upload=新的ServletFileUpload(工厂);
upload.setFileSizeMax(最大文件大小);
upload.setSizeMax(请求大小);
java.io.PrintWriter out=response.getWriter();
试一试{
//解析请求的内容以提取文件数据
List formItems=upload.parseRequest(请求);
out.println(“字段数:+formItems.size());
迭代器iter=formItems.Iterator();
//迭代窗体的字段
while(iter.hasNext())
{
out.println(“内部while循环”);
FileItem=(FileItem)iter.next();
//仅处理非表单字段的字段
如果(!item.isFormField())
{
字符串temp=item.getFieldName();
out.println(“参数名称”+temp);
if(临时等于(“上载文件”))
{
字符串文件名=新文件(item.getName()).getName();
文件名=文件名+“.txt”;
out.println(“文件名”+文件名);
FileService FileService=fileservicecfactory.getFileService();
gsfileoptionsbuilderoptionsbuilder=新的GSFileOptionsBuilder()
.setBucket(BUCKETNAME)
.setKey(文件名)
.setMimeType(“text/html”)//音频/mp3文本/html
.setAcl(“公开阅读”)
.addUserMetadata(“myfield1”、“我的字段值”);
AppEngineFile可写文件=
fileService.createNewGSFile(optionsBuilder.build());
//打开一个通道写入它
布尔锁=假;
文件写入通道写入通道=
openWriteChannel(可写文件,锁);
//写入通道的不同标准Java方式
//都是可能的。这里我们使用PrintWriter:
InputStream InputStream=item.getInputStream();
int readBytes=0;
字节[]缓冲区=新字节[10000];
而((readBytes=inputStream.read(缓冲区,0,10000))!=-1)
{
writeChannel.write(ByteBuffer.wrap(缓冲区));
}
inputStream.close();
writeChannel.closeFinally();
response.getWriter().println(“完成写入…”);
}
else if(温度等于(“参数1”))
{
out.println(“内部参数1”);
//字符串param1Val=新文件(item.getName()).getName();
//BUCKETNAME=param1Val;
}
else if(温度等于(“参数2”))
{
out.println(“内部参数2”);
//字符串param2Val=新文件(item.getName()).getName();
//BUCKETNAME=param2Val;
}
}
}
setAttribute(“消息”,“上传成功!”);
}捕获(例外情况除外){
setAttribute(“消息”,“出现错误:”+ex.getMessage());
}
}
选项包括:

a、 与表单一起使用以上载大文件,或

b、 使用您的方法,然后解码、解析上载并自己在servlet中写入blobstore(文件需要小于32MB),或者


c、 使用直接写入GCS,然后将上载的文件名发布到您的应用程序。

此外,我曾尝试在Amazon Bucket S3和Windows Azure上上载文件,它们提供了直接的方式来完成相同的操作。我在Google上最难找到这一点。奇怪!!感谢您的回复@Stuart..我无法
 Servlet code to handle file upload and save to Google storage--

 @MultipartConfig   
 @SuppressWarnings("serial")
   public class SecondtrygoogleServlet extends HttpServlet 
   {
public static String BUCKETNAME = "androidbucket";
public static String FILENAME = "shikhatry.txt";

private static final long serialVersionUID = 1L;


private static final int THRESHOLD_SIZE = 1024 * 1024 * 3; // 3MB
private static final int MAX_FILE_SIZE = 1024 * 1024 * 40; // 40MB
private static final int REQUEST_SIZE = 1024 * 1024 * 50; // 50MB



public void doPost(HttpServletRequest request, HttpServletResponse response)
        throws ServletException, IOException 
{
    // checks if the request actually contains upload file
    if (!ServletFileUpload.isMultipartContent(request)) {
        // if not, we stop here
        return;
    }

    response.setContentType("text/plain");
    response.getWriter().println("Hello, test1 world");

    // configures some settings
    DiskFileItemFactory factory = new DiskFileItemFactory();
    factory.setSizeThreshold(THRESHOLD_SIZE);
    factory.setRepository(new File(System.getProperty("java.io.tmpdir")));

    ServletFileUpload upload = new ServletFileUpload(factory);
    upload.setFileSizeMax(MAX_FILE_SIZE);
    upload.setSizeMax(REQUEST_SIZE);
    java.io.PrintWriter out = response.getWriter( );

    try {
            // parses the request's content to extract file data
            List<?> formItems = upload.parseRequest(request);
            out.println("Number of fields: " + formItems.size());
            Iterator<?> iter = formItems.iterator();


            // iterates over form's fields
            while (iter.hasNext()) 
            {
                out.println("Inside while loop");
                FileItem item = (FileItem) iter.next();
                // processes only fields that are not form fields
                if (!item.isFormField()) 
                {

                    String temp = item.getFieldName();
                    out.println("Parameter Name"+temp);

                    if(temp.equals("uploadedfile"))
                    {
                        String fileName = new File(item.getName()).getName();
                        FILENAME = fileName+".txt";
                        out.println("Filename"+fileName);


                        FileService fileService = FileServiceFactory.getFileService();
                        GSFileOptionsBuilder optionsBuilder = new GSFileOptionsBuilder()
                        .setBucket(BUCKETNAME)
                        .setKey(FILENAME)
                        .setMimeType("text/html") //audio/mp3 text/html
                        .setAcl("public_read")
                        .addUserMetadata("myfield1", "my field value");


                     AppEngineFile writableFile =
                         fileService.createNewGSFile(optionsBuilder.build());

                     // Open a channel to write to it
                     boolean lock = false;
                     FileWriteChannel writeChannel =
                         fileService.openWriteChannel(writableFile, lock);


                     // Different standard Java ways of writing to the channel
                     // are possible. Here we use a PrintWriter:

                     InputStream inputStream = item.getInputStream();
                     int readBytes = 0;
                     byte[] buffer = new byte[10000];



                     while ((readBytes = inputStream.read(buffer, 0, 10000)) != -1) 
                     {
                        writeChannel.write(ByteBuffer.wrap(buffer));

                     }

                     inputStream.close();

                     writeChannel.closeFinally();
                     response.getWriter().println("Done writing...");

                }
                else if(temp.equals("param1"))
                {
                    out.println("Inside param1");
                    //String param1Val = new File(item.getName()).getName();                        
                    //BUCKETNAME = param1Val;
                }
                else if(temp.equals("param2"))
                {
                    out.println("Inside param2");
                    //String param2Val = new File(item.getName()).getName();

                    //BUCKETNAME = param2Val;


                }
            }
        }
        request.setAttribute("message", "Upload has been done successfully!");
    } catch (Exception ex) {
        request.setAttribute("message", "There was an error: " + ex.getMessage());
    }


}