java multipartfile 转 file,将MultipartFile转换为java.io.File,而不复制到本地机器

I have a Java Spring MVC web application. From client, through AngularJS, I am uploading a file and posting it to Controller as webservice.

In my Controller, I am gettinfg it as MultipartFile and I can copy it to local machine.

But I want to upload the file to Amazone S3 bucket. So I have to convert it to java.io.File. Right now what I am doing is, I am copying it to local machine and then uploading to S3 using jets3t.

Here is my way of converting in controller

MultipartHttpServletRequest mRequest=(MultipartHttpServletRequest)request;

Iterator itr=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.

Then I am using FIleCopyUtils of SpringFramework

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);

So it will create a new file in the local machine. That file I am uplaoding in S3

S3Object fileObject = new S3Object(newFile);

s3Service.putObject("myBucket", fileObject);

It creates file in my local system. I don't want to create.

Without creating a file in local system, how to convert a MultipartFIle to java.io.File?

解决方案

MultipartFile, by default, is already saved on your server as a file when user uploaded it.

From that point - you can do anything you want with this file.

There is a method that moves that temp file to any destination you want.

http://docs.spring.io/spring/docs/3.0.x/api/org/springframework/web/multipart/MultipartFile.html#transferTo(java.io.File)

This API accepts input stream and you can do anything you want with it. Default implementation (usually commons-multipart) saves it to temp dir as a file.

But other problem stays here - if S3 API accepts a file as a parameter - you cannot do anything with this - you need a real file. If you want to avoid creating files at all - create you own S3 API.

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值