图片上传文件流格式转换 File文件流转为MultipartFile流详解

版权声明:本文为博主原创文章,如需转载,敬请注明转载链接 https://blog.csdn.net/guobinhui/article/details/88576897

10万+IT人都在关注的IT技术博客,实用的技术干货持续更新......

通常从界面上传的文件,后台接口都用MultipartFile格式的文件流接收,如果要直接对物理磁盘目录里的文件进行操作,则只能实用File流进行操作,有时由于一些定制化的需求,需要对File流和MultipartFile流转换,笔者分享一个已经完美实现的转换工具类,如果觉得对您有帮助,敬请点赞并分享给更多需要的人,废话不多说,直接上代码:

package com.demo.utils;

import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;
import java.io.OutputStream;

import org.apache.commons.fileupload.FileItem;
import org.apache.commons.fileupload.FileItemFactory;
import org.apache.commons.fileupload.disk.DiskFileItemFactory;
import org.springframework.web.multipart.MultipartFile;
import org.springframework.web.multipart.commons.CommonsMultipartFile;

/**
 * 创建时间:2019年3月8日 下午4:25:55
 * 项目名称:shsc-batchUpload-server
 * 类说明:File流转为MultipartFile流
 * @author guobinhui
 * @since JDK 1.8.0_51
 */
public class FileCovertUtils {

	public static void main(String[] args) {
        try {   
            String picPath = "D:/originalfile/10001.png";
            File f = new File(picPath);
            MultipartFile file = getMulFileByFile(f);
            System.out.println(file.getOriginalFilename());
        } catch(Exception e) {
        	e.printStackTrace();
        }
	}
	
	public static MultipartFile getMulFileByFile(File file) { 
        FileItem fileItem = createFileItem(file.getPath(),file.getName());  
        MultipartFile mfile = new CommonsMultipartFile(fileItem);  
        return mfile;  
    }
	
	public static FileItem createFileItem(String filePath,String fileName){  
        String fieldName = "file";
        FileItemFactory factory = new DiskFileItemFactory(16, null);   
        FileItem item = factory.createItem(fieldName, "text/plain", false,fileName);  
        File newfile = new File(filePath);  
        int bytesRead = 0;  
        byte[] buffer = new byte[8192];  
        try  
        {  
            FileInputStream fis = new FileInputStream(newfile);  
            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;  
    } 
}

更多JavaEE资料请关注下面公众号,欢迎广大开发者朋友一起交流。笔者电话(微信):18629374628

展开阅读全文

没有更多推荐了,返回首页