spring 文件上传原理 (在非spring环境中可以使用)

前提是必须引入spring相关jar包。

 

importorg.springframework.web.multipart.MultipartFile;

importorg.springframework.web.multipart.MultipartHttpServletRequest;

importorg.springframework.web.multipart.commons.CommonsMultipartResolver;

 

 

public voidupload2(HttpServletRequest request, HttpServletResponse response) throwsException

{

 

 

MultipartHttpServletRequestmultipartRequest = null;

//创建上传处理类

CommonsMultipartResolvermultipartResolver=new CommonsMultipartResolver();

//设置上传限制等

multipartResolver.setDefaultEncoding("UTF-8");

multipartResolver.setMaxUploadSize(Config.getFileMaxSize());

try

{

//是否文件上传

if(multipartResolver.isMultipart(request))

{

  //解析上传

  multipartRequest =multipartResolver.resolveMultipart(request);

  //获取文件名

  MultipartFile multipartFile=  multipartRequest.getFile("file1");

   //获取原始文件名        

  String originalFilename =multipartFile.getOriginalFilename();

 //获取文件流,可以进行处理

    multipartFile.getInputStream()

  //直接保存文件

  getInputStream.transferTo(newFile("test.jpg"));

  

  }

}

finally

{

 //清除临时文件

if(multipartRequest!=null)

{

multipartResolver.cleanupMultipart(multipartRequest);

}

}

 

 

}

你可能感兴趣的:(Spring,Web)