J**a中String类型转MultipartFile

时间:2018.06.12 发布人:大漠3333

J**a中String类型转MultipartFile

已解决问题

谷歌大漠3333用户在2018.06.12提交了关于“史铁生J**a中String类型转MultipartFile”的提问,欢迎大家涌跃发表自己的观点。目前共有1个回答,最后更新于2024-07-17T03:05:42。希望大家能够帮助她。

详细问题描述及疑问:期待您的答案,当代劳模,所有人都应该向你学习 !

希望以下的回答,能够帮助你。

第1个回答

用户名:sdnb**dnasbdvn  

packagecom.xiaojd.test;

importj**a.io.File;

importj**a.io.FileInputStream;

i来自mportj**a.io.IOException;

importj**a.io.OutputStream;

importorg.apa十che.commons.fileupload.FileItem;

importorg.apache.commons.fileupl问答oad.FileItemFactory;

importorg.apache.commons.fileupload.dis府极计东愿雷紧另家消专k.DiskFileIte迅传封mFactory;

importorg.springframework.web.multipart.MultipartFile;

importorg.springframework.web.multipart.commons.CommonsMultipartFile;

publicclas齐sTest{

publicstaticvoidmain(Strin冲领背点积甚社问g[]args){

StringpicPath="D://pic//1.png";

MultipartFilefile=getMulFileByPath(picPath);

try{

byte[]bytes=file.getBytes();

for(byteb:bytes){

System.out.print(b);

}

}catch(IOExceptione){

e.printStackTrace妈缺求去群胡例决下远();

}

//图片上传

picUpload(file);

}

privatestaticvoidpicUpload(Mu去沉座专那征送ltipartFil很由红否艺差由efile){

//图片上传

if(file!=**ll){//判断上传的文件是否为空

Stringpath=**ll;//文件路径

Stringtype=**ll;//文件类型

Stringf夜九完工ileName=file.g具etOriginalFilename();//文件原名称

System.out.println("上传的文件原名称:"+fileName);

//判断文件类型

type=fileName.indexOf(".")!=-1?fileName.substring(fileName.lastInde清第获完喜开乱xOf(".")+延1,fileNa行始盐承须概me.length()):null;

if(type!=**ll){//判断文件类型沙是否为空

if("GIF".equals(type.toUpperCase())||"PNG".equals(type.toUpperCase())||"JP她准触G".equals(type.toUpperCase())){

//项目在容器中翻假山顶牛美读项实际发布运行的根路径

//Stringre奏气判的严续alPath=request.getSession().getServletContext().getRealPath("/");

//哥哥自己写的路径

StringrealPath="F://pic//";

//自定义的文件名称

StringtrueFileName=fileName;

//设置存放图片文件的路径

path=realPath+trueFileName;

System.out.println("存放图片文件的路径:"+path);

//转存文件到指定的路径

try{

file.transferTo(newFile(path));

}catch(Exceptione){

e.printStackTrace();

}

System.out.println("文件成功上传到指定目录下");

}else{

System.out.println("不是我们想要的文件类型,请按要求重新上传");

}

}else{

System.out.println("文件类型为空");

}

}

System.out.println("没有找到相对应的文件");

}

privatestaticMultipartFilegetMulFileByPath(StringpicPath){

FileItemfileItem=createFileItem(picPath);

MultipartFilemfile=newCommonsMultipartFile(fileItem);

returnmfile;

}

privatestaticFileItemcreateFileItem(StringfilePath)

{

FileItemFactoryfactory=newDiskFileItemFactory(16,**ll);

StringtextFieldName="textField";

int**m=filePath.lastIndexOf(".");

StringextFile=filePath.substring(**m);

FileItemitem=factory.createItem(textFieldName,"text/plain",true,

"MyFileName"+extFile);

Filenewfile=newFile(filePath);

intbytesRead=0;

byte[]buffer=newbyte[8192];

try

{

FileInputStreamfis=newFileInputStream(newfile);

OutputStreamos=item.getOutputStream();

while((bytesRead=***.read(buffer,0,8192))

!=-1)

{

os.write(buffer,0,bytesRead);

}

os.close();

fis.close();

}

catch(IOExceptione)

{

e.printStackTrace();

}

returnitem;

}

}