java文件上传-图片上传

java文件上传-图片上传

java使用springmvc实现图片上传

注意事项:

必需要有commons-fileupload,commons-io,这些jar包

springmvc的配置文件中必须要有

否则会报异常:org.apache.catalina.connector.RequestFacade cannot be cast to org.springframework.web.multipart.MultipartHttpServletRequest。

html代码如下:

java代码如下:

@RequestMapping(value="/imgUpload",method=RequestMethod.POST)

@ResponseBody

public String imgUpload(HttpServletRequest request, HttpServletResponse response)throws IOException{

MultipartHttpServletRequest multiPartRequest = (MultipartHttpServletRequest)request;

MultipartFile multiPartFile = multiPartRequest.getFile("upload");

String name = multiPartFile.getName();//返回表单里面上传图片参数的名字,eg:upload

String originalName = multiPartFile.getOriginalFilename();//返回客户端文件的原始名称,eg:atv1.png

String contentType = multiPartFile.getContentType();//文件内容类型,eg:image/png

long size = multiPartFile.getSize();//返回文件大小,单位是字节

byte[] bytes = multiPartFile.getBytes();//返回文件内容的字节数组

response.setCharacterEncoding("utf-8");

PrintWriter out = response.getWriter();

String callback = request.getParameter("CKEditorFuncNum");

//对文件类型进行判断筛选,只处理.jpg,.png,.gif的图片

boolean isSpecifiedImgType = false;

String imgFileSuffix = "";//图像文件的后缀

String[] imgSuffixs = {".jpg", ".png", ".gif"};

for(String imgSuffix : imgSuffixs){

if(originalName.endsWith(imgSuffix)){

isSpecifiedImgType = true;

imgFileSuffix = imgSuffix;

break;

}

}

if(!isSpecifiedImgType){

out.println("

out.println("window.parent.CKEDITOR.tools.callFunction(" + callback

+ ",''," + "'文件格式不正确(必须为.jpg/.png/.gif文件)');");

out.println("");

return null;

}

//对文件大小进行判断筛选

if(size > 600*1024){

out.println("

out.println("window.parent.CKEDITOR.tools.callFunction(" + callback

+ ",''," + "'文件大小不得大于600k');");

out.println("");

return null;

}

//文件的前缀,eg:201503271453000025

String imgFilePrefix = new SimpleDateFormat("yyyyMMddHHmmssssss").format(Calendar.getInstance().getTime());

String newImgFileName = imgFilePrefix + imgFileSuffix;

String uploadPathStr = getUploadPath();

File uploadPath = new File(uploadPathStr);

if(!uploadPath.exists()){

uploadPath.mkdirs();

}

InputStream in = multiPartFile.getInputStream();//返回一个输入流来读取文件内容

File targetFile = new File(uploadPathStr, newImgFileName);

OutputStream os = new FileOutputStream(targetFile);

byte[] buffer = new byte[1024];

int length = 0;

while((length=in.read(buffer))>0){

os.write(buffer, 0, length);

}

in.close();

os.close();

//String imgAdressOnServer = uploadPathStr + originalName;

//这个值在预览里面相当于图片的src

String imgAdressOnServer = getDomainPath(newImgFileName);

logger.info("专题定制上传图片的域名访问路径为:" + imgAdressOnServer);

out.println("

out.println("window.parent.CKEDITOR.tools.callFunction(" + callback

+ ",'" + imgAdressOnServer + "','')");

out.println("");

return null;

}

使用org.apache.commons.io.FileUtils这个类可以很方便的快速复制文件,使用示例如下:

@Controller

@RequestMapping("/courses")

public class CourseController {

@RequestMapping(value="/doUpload", method=RequestMethod.POST)

public String doUploadFile(@RequestParam("file") MultipartFile file) throws IOException{

if(!file.isEmpty()){

FileUtils.copyInputStreamToFile(file.getInputStream(), new File("c:\\temp\\", System.currentTimeMillis()+ file.getOriginalFilename()));

}

return "success";

}

@RequestMapping(value="/doUpload2", method=RequestMethod.POST)

public String doUploadFile2(MultipartHttpServletRequest multiRequest) throws IOException{

Iterator filesNames = multiRequest.getFileNames();

while(filesNames.hasNext()){

String fileName =filesNames.next();

MultipartFile file = multiRequest.getFile(fileName);

if(!file.isEmpty()){

FileUtils.copyInputStreamToFile(file.getInputStream(), new File("c:\\temp\\", System.currentTimeMillis()+ file.getOriginalFilename()));

}

}

return "success";

}

}