Java 后台实现上传图片的接收并保存

1.java

public static File uploadFilesSpecifyPath(HttpServletRequest request, String fileDir, String Filedata) throws Exception {
	MultipartFile mf = null;
	File mff = null;
	if (!(request instanceof MultipartHttpServletRequest)) {
		String errorMsg = "your post form is not support ENCTYPE='multipart/form-data' ";
		log.error(errorMsg);

		throw new RuntimeException(errorMsg);
	}
	MultipartHttpServletRequest multipartRequest = (MultipartHttpServletRequest) request;
	List multipartFiles = multipartRequest.getFiles(Filedata);
	if (null != multipartFiles && multipartFiles.size() > 0) {
		mf = multipartFiles.get(0);
		String realPath = StringUtils.mergeStringWithSeparator(fileDir,mf.getOriginalFilename());
		File source = new File(realPath);
		try {
			mf.transferTo(source);
			mff = source;
			log.debug("Upload file " + source.getAbsoluteFile() + " Success!");
		} catch (Exception e) {
			String errorMsg = "Upload file " + source.getAbsoluteFile() + " Error!" + e.getMessage();
			log.error(errorMsg);
			throw new RuntimeException(errorMsg);

		}
	}
	return mff;
}
第一个参数为request请求,第二个参数为图片保存的路径,第三个参数类似前段的name属性


2.StringUtils中的方法

/**
* 返回斜杠拼接的字符串
* @param args
* @return
 */
public static String mergeStringWithSeparator(String...args){
	StringBuilder sb=new StringBuilder();
	for (String arg : args) {
		sb.append(arg);
		sb.append(File.separator);
	}
		
	return sb.substring(0, sb.length()-1).toString();
}


你可能感兴趣的:(Java)