我正在使用Bluemix Object Storage服务和Java通过编码将文件上传到Object Storage。这是我的代码snipet,用于将文件上传到Object Storage:
@Override
protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
ObjectStorageService objectStorage = authenticateAndGetObjectStorageService();
System.out.println("Storing file in post ObjectStorage...0508");
String containerName = request.getParameter("container");
String fileName = request.getParameter("file");
System.out.println("containerName in post: "+containerName +"And file name"+fileName);
if(containerName == null || fileName == null){ //No file was specified to be found, or container name is missing
response.sendError(HttpServletResponse.SC_NOT_FOUND);
System.out.println("File not found.");
return;
}
try {
final InputStream fileStream = request.getInputStream();
System.out.println("fileStream: "+fileStream);
Payload<InputStream> payload = new PayloadClass(fileStream);
objectStorage.objects().put(containerName, fileName, payload);
System.out.println("Successfully stored file in ObjectStorage!");
} catch (Exception e) {
System.out.println("Exception in uploaidng +"+e.toString());
// TODO: handle exception
}
}
但是,将0kb文件上载到对象存储。
答案 0 :(得分:0)
请使用getData()从InputStream中提取二进制文件。以下是openstack4j getData docs。
答案 1 :(得分:0)
我能使其工作的唯一方法是将MultiPart注释放在Servlet上
@WebServlet("/objectStorage")
@MultipartConfig
public class SimpleServlet extends HttpServlet
获取部分而不是整个inputStream:
Part filePart = request.getPart("fileToUpload"); // Retrieves <input type="file" name="fileToUpload">
InputStream fileContent = filePart.getInputStream();
在html表单上将enctype设置为multipart / formdata
<form action="objectStorage" method="post" enctype="multipart/form-data">
我的整个代码就是这样:
HTML:
<form action="objectStorage" method="post" enctype="multipart/form-data">
Select image to upload:
<input type="file" name="fileToUpload" id="fileToUpload">
<input type="text" name="nome" id="nome">
<input type="submit" value="Upload Image" name="submit">
</form>
Java代码:
@Override
protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
ObjectStorageService objectStorage = authenticateAndGetObjectStorageService();
System.out.println("Storing file in ObjectStorage...");
String containerName = "abc";
String fileName = request.getParameter("nome");
if (containerName == null || fileName == null) { //No file was specified to be found, or container name is missing
response.sendError(HttpServletResponse.SC_NOT_FOUND);
System.out.println("File not found.");
return;
}
try {
Part filePart = request.getPart("fileToUpload"); // Retrieves <input type="file" name="file">
InputStream fileContent = filePart.getInputStream();
Payload<InputStream> payload = new PayloadClass(fileContent);
objectStorage.objects().put(containerName, fileName, payload);
System.out.println("Upload Successful");
} catch (Exception e) {
System.out.println(e);
}
}