我有一个Java Spring MVC Web应用程序.从客户端到AngularJS,我上传文件并将其作为webservice发布到Controller.
在我的控制器中,我将其作为MultipartFile获取,我可以将其复制到本地计算机.
但我想将文件上传到Amazone S3存储桶.所以我必须将其转换为java.io.File.现在我正在做的是,我将它复制到本地机器,然后使用jets3t上传到S3 .
这是我在控制器中转换的方式
MultipartHttpServletRequest mRequest=(MultipartHttpServletRequest)request; Iteratoritr=mRequest.getFileNames(); while(itr.hasNext()){ MultipartFile mFile=mRequest.getFile(itr.next()); String fileName=mFile.getOriginalFilename(); fileLoc="/home/mydocs/my-uploads/"+date+"_"+fileName; //date is String form of current date.
然后我使用SpringFramework的FIleCopyUtils
File newFile = new File(fileLoc); // if the directory does not exist, create it if (!newFile.getParentFile().exists()) { newFile.getParentFile().mkdirs(); } FileCopyUtils.copy(mFile.getBytes(), newFile);
因此它将在本地计算机中创建一个新文件.那个文件我在S3上面了
S3Object fileObject = new S3Object(newFile); s3Service.putObject("myBucket", fileObject);
它在我的本地系统中创建文件.我不想创造.
如果不在本地系统中创建文件,如何将MultipartFIle转换为java.io.File?
默认情况下,MultipartFile在用户上传时已作为文件保存在服务器上.从那时起 - 您可以使用此文件执行任何操作.有一种方法可以将临时文件移动到您想要的任何目标. http://docs.spring.io/spring/docs/3.0.x/api/org/springframework/web/multipart/MultipartFile.html#transferTo(java.io.File)
但是MultipartFile只是API,你可以实现任何其他的MultipartResolver http://docs.spring.io/spring/docs/3.0.x/api/org/springframework/web/multipart/MultipartResolver.html
此API接受输入流,您可以使用它执行任何操作.默认实现(通常是commons-multipart)将其作为文件保存到临时目录.
但其他问题仍然存在 - 如果S3 API接受一个文件作为参数 - 你不能对此做任何事情 - 你需要一个真实的文件.如果你想避免创建文件 - 创建自己的S3 API.
问题已经超过一年了,所以我不确定OP提供的jets35链接当时是否有以下代码段.
如果您的数据不是
File
或者String
您可以使用任何输入流作为数据源,但您必须手动设置Content-Length.// Create an object containing a greeting string as input stream data. String greeting = "Hello World!"; S3Object helloWorldObject = new S3Object("HelloWorld2.txt"); ByteArrayInputStream greetingIS = new ByteArrayInputStream(greeting.getBytes()); helloWorldObject.setDataInputStream(greetingIS); helloWorldObject.setContentLength( greeting.getBytes(Constants.DEFAULT_ENCODING).length); helloWorldObject.setContentType("text/plain"); s3Service.putObject(testBucket, helloWorldObject);
事实证明,您不必先创建本地文件.作为@Boris建议你可以喂S3Object
用Data Input Stream
,Content Type
并且Content Length
你会从中获取MultipartFile.getInputStream()
,MultipartFile.getContentType()
并MultipartFile.getSize()
分别.