我正在尝试将文件上传到 Google Cloud Storage。我的Servlet代码是
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>
fileUpload函数将文件保存到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
此外,将其与 Angular 中的 UI 集成并在本地进行测试后,我遇到了这个问题
Cross-Origin Request Blocked Reason: CORS header 'Access-Control-Allow-Origin' missing
我尝试解决此问题,但没有找到与 google appengine 相对应的解决方案。
最初我试图通过此代码上传图像,但在不久的将来,相同的代码将用于将 .pdf 和 .html 文件上传到 GCS。
以供参考:
我正在使用 Google Endpoints 来满足与客户端的其他数据通信需求。客户端是一个用 Angular 构建的 web 应用程序,但它将扩展到 android 和 ios。
任何帮助将不胜感激。
谢谢
更新 1/8/2016
现在我正在服务器上获取文件,但我不知道在将文件发送到 Google Cloud Storage 之前必须将其临时保存在哪里。关于将文件存储在
war\WEB-INI\
我面临的例外是
java.security.AccessControlException: access denied ("java.io.FilePermission" "\war\WEB-INI\profile.png" "read")