我試圖將文件上傳到Google雲端存儲。我的servlet代碼是通過appengine將文件上傳到Google雲端存儲
public class UploadFile extends HttpServlet {
private final String BUCKET = "XXXXXXXXX";
private boolean isMultipart;
private String filePath;
private int maxFileSize = 5 * 1024 * 1024;
private int maxMemSize = 5 * 1024 * 1024;
private File file ;
public void init(){
// Get the file location where it would be stored.
filePath =
getServletContext().getInitParameter("file-upload");
}
public void doPost(HttpServletRequest request,
HttpServletResponse response)
throws ServletException, java.io.IOException {
// Check that we have a file upload request
isMultipart = ServletFileUpload.isMultipartContent(request);
response.setContentType("text/html");
java.io.PrintWriter out = response.getWriter();
if(!isMultipart){
out.println("<html>");
out.println("<head>");
out.println("<title>Servlet upload</title>");
out.println("</head>");
out.println("<body>");
out.println("<p>No file uploaded</p>");
out.println("</body>");
out.println("</html>");
return;
}
DiskFileItemFactory factory = new DiskFileItemFactory();
// maximum size that will be stored in memory
factory.setSizeThreshold(maxMemSize);
// Location to save data that is larger than maxMemSize.
factory.setRepository(new File("/temp/image/"));
// Create a new file upload handler
ServletFileUpload upload = new ServletFileUpload(factory);
// maximum file size to be uploaded.
upload.setSizeMax(maxFileSize);
try{
// Parse the request to get file items.
List fileItems = upload.parseRequest(request);
// Process the uploaded file items
Iterator i = fileItems.iterator();
out.println("<html>");
out.println("<head>");
out.println("<title>Servlet upload</title>");
out.println("</head>");
out.println("<body>");
while (i.hasNext())
{
FileItem fi = (FileItem)i.next();
if (!fi.isFormField())
{
// Get the uploaded file parameters
String fieldName = fi.getFieldName();
String fileName = fi.getName();
String contentType = fi.getContentType();
boolean isInMemory = fi.isInMemory();
long sizeInBytes = fi.getSize();
// Write the file
if(fileName.lastIndexOf("\\") >= 0){
file = new File(filePath +
fileName.substring(fileName.lastIndexOf("\\"))) ;
}else{
file = new File(filePath +
fileName.substring(fileName.lastIndexOf("\\")+1)) ;
}
String path = Events.uploadFile (fileName, "image/*", file, BUCKET);
// fi.write(file) ;
out.println("Uploaded Filename: " + fileName + "<br>"+ " File Path:"+ path);
}
}
out.println("</body>");
out.println("</html>");
}catch(Exception ex) {
System.out.println(ex);
}
}
public void doGet(HttpServletRequest request,
HttpServletResponse response)
throws ServletException, java.io.IOException {
throw new ServletException("GET method used with " +
getClass().getName()+": POST method required.");
}
}
的web.xml
<servlet>
<servlet-name>UploadFile</servlet-name>
<servlet-class>XXXXXXXXXX.UploadFile</servlet-class>
</servlet>
<servlet-mapping>
<servlet-name>UploadFile</servlet-name>
<url-pattern>/uploadManager/UploadFile</url-pattern> //Based on your original URL
</servlet-mapping>
文件上傳功能,文件保存到GCS
public static String uploadFile (String name, String contentType, File file, String bucketName)
throws IOException, GeneralSecurityException
{
InputStreamContent contentStream = new InputStreamContent (contentType, new FileInputStream (file));
// Setting the length improves upload performance
contentStream.setLength (file.length());
StorageObject objectMetadata = new StorageObject()
// Set the destination object name
.setName (name)
// Set the access control list to publicly read-only
.setAcl (Arrays.asList (new ObjectAccessControl().setEntity ("allUsers").setRole ("READER")));
// Do the insert
Storage client = StorageFactory.getService();
Storage.Objects.Insert insertRequest = client.objects().insert (bucketName, objectMetadata, contentStream);
insertRequest.execute();
return "https://storage.cloud.google.com/" + BUCKET + "/" + file.getName();
}
但是當我嘗試了一些API測試客戶端來測試這個提示錯誤
org.apache.commons.fileupload.FileUploadException: the request was rejected because no multipart boundary was found
Furt她與UI這是在角整合,並在本地測試之後,我面臨這個問題
Cross-Origin Request Blocked Reason: CORS header 'Access-Control-Allow-Origin' missing
我試圖解決這個問題,但發現相當於谷歌AppEngine上無解。
最初我試圖通過這個代碼,但在不久的將來,同樣的代碼上傳圖像將被用來.pdf和.html文件上傳到GCS。
僅供參考: 我正在使用Google Endpoints來滿足客戶端的其他數據通信需求。客戶端是一個在Angular中構建的webapp,但它將被擴展到android和ios。
任何幫助將不勝感激。
謝謝
UPDATE 2016年1月8日
現在我得到的服務器上的文件,但我不知道我要的文件臨時保存它發送到谷歌雲存儲前。在
war\WEB-INI\
和我面臨的例外存儲文件
java.security.AccessControlException: access denied ("java.io.FilePermission" "\war\WEB-INI\profile.png" "read")
「這裏是你的服務帳戶JSON的URL - 我使用GOOGLE DRIVE直接下載鏈接到我的JSON文件」如何生成服務帳戶JSON?你能舉一個結構的例子嗎? – dina
@ user5980143你必須從谷歌控制檯下載它。 –
如果我已經在谷歌應用程序引擎中運行,我不需要「GoogleCreditial」權限? –