java将File转换成MultipartFile

项目中遇到将网络图片下载到本地,然后加入签章后再上传到文件服务器。由于下载后的文件是File类型,上传接口接受的是MultipartFile类型,于是需要将File转换成MultipartFile。
1.引入commons-fileupload的jar


            commons-fileupload
            commons-fileupload
            1.3.2

2.定义将文件转换成FileItem的方法

import org.apache.commons.io.FilenameUtils;
import org.apache.commons.fileupload.FileItem;
import org.apache.commons.fileupload.FileItemFactory;
import org.apache.commons.fileupload.disk.DiskFileItemFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
import org.springframework.web.multipart.MultipartFile;
import org.springframework.web.multipart.commons.CommonsMultipartFile;

  /**
     * 将file转换成fileItem
     * @param file
     * @param fieldName
     * @return
     */
    private FileItem  getMultipartFile(File file, String fieldName){
        FileItemFactory factory = new DiskFileItemFactory(16, null);
        FileItem item = factory.createItem(fieldName, "text/plain", true, file.getName());
        int bytesRead = 0;
        byte[] buffer = new byte[8192];
        try {
            FileInputStream fis = new FileInputStream(file);
            OutputStream os = item.getOutputStream();
            while ((bytesRead = fis.read(buffer, 0, 8192)) != -1) {
                os.write(buffer, 0, bytesRead);
            }
            os.close();
            fis.close();
        } catch (IOException e) {
            e.printStackTrace();
        }
        return item;
    }

3.调用

 File file = new File("C://");          
 FileItem fileItem = this.getMultipartFile(file,"templFileItem");
 MultipartFile multipartFile = new CommonsMultipartFile(fileItem);

你可能感兴趣的:(java)