3 일 동안 Google 애플리케이션 엔진에서 작업 중이며 마지막으로이 문제가 발생하여 해결할 수 없었습니다. 많은 연구가 진행되었지만 설득력있는 자료를 찾을 수있었습니다. Mandroid를 통해 GAE에 파일 업로드
Google 애플리케이션 엔진 계정을 설정 한 후 애플리케이션 URL "my-app-id.appspot.com/myservlet"을 호출하면 간단한 서블릿 GAE에서 Google 버킷에 .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);
uploadservlet.java
An example @ Complete Sample App at this link:
https://developers.google.com/appengine/docs/java/googlestorage/overview
내가 여러 부분을 사용하여 POST 메소드를 통해 일부 파일을 보낼 때 이제 내 문제가되어, 서블릿 @ 애플 리케이션 엔진 나던 작업과 나는 일식에서 오류 메시지 "Filenotfound"를 얻는다. 이 방법도 옳다면 안드로이드 측
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);
에서
된 .java 파일이 궁금입니다. 다른 솔루션이 아니라면 .. 나는 또한 blobstorage를 보았다. 그러나 그것은 같은 것을한다, 버킷에 파일을 쓰지 마라. .. 도와주세요. 나에게 도움이된다. .. 무엇이라도 위대하고 감사하게 될 것이다!
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());
}
}
또한 Amazon Bucket S3 및 Windows Azure에서 파일을 업로드하려고 시도했으며 동일한 작업을 수행하는 데 직접적인 방법을 제공합니다. 나는 Google에서 이것을 알아내는 가장 어려운 시간을 보내고있다. 이상한!! –