Controler层里面代码内容
@RequestMapping(value="/uploadImg", method=RequestMethod.POST)
@ResponseBody
public String uploadImgController(@RequestParam(value="img")MultipartFile img){
File f = new File("/images");
try{
FileUtils.copyInputStreamToFile(img.getInputStream(), f);
}catch(Exception e){
e.printStackTrace();
}
return "上传成功";
}
new File里面的路径是文件保存路径
HTML文件内容
<form action="http://localhost/component/common/uploadImg" method="post" enctype="multipart/form-data">
头像:<input type="file" name="img" /><br/>
<input type="image" src="./images/img_submit.gif" />
</form>
以上是直接上传文件到指定目录下,如果需要得到储存图片的路径,修改如下:
controller层
@RequestMapping(value="/uploadImg", method=RequestMethod.POST)
@ResponseBody
public String uploadImgController(@RequestParam(value="img")MultipartFile img, HttpServletResponse response){
JSONObject result = new JSONObject();
boolean flag = true;
try {
flag = pictureUploadService.upload(img, result);
} catch (Exception e) {
result.put("mess", "调用失败");
flag = false;
e.printStackTrace();
}
result.put("flag", flag);
response.setContentType("text/html;charset=UTF-8");
//解决跨域名访问问题
response.setHeader("Access-Control-Allow-Origin", "*");
return result.toString();
}
service层
/**
* 上传图片
* @param file
* @param params
* @return
* @throws Exception
*/
public boolean upload(MultipartFile file, JSONObject params) throws Exception{
//过滤合法的文件类型
String fileName = file.getOriginalFilename();
String suffix = fileName.substring(fileName.lastIndexOf(".")+1);
String allowSuffixs = "gif,jpg,jpeg,bmp,png,ico";
if(allowSuffixs.indexOf(suffix) == -1){
params.put("resultStr", "not support the file type!");
return false;
}
//生成唯一的文件名
public String getUniqueFileName() {
String str = UUID.randomUUID().toString();
return str.replace("-", "");
}
//获取网络地址、本地地址头部
Properties config = new Properties();
config.load(this.getClass().getClassLoader().getResourceAsStream("config.properties"));
String urlPath = config.getProperty("urlRoot");
String localPath = config.getProperty("localRoot");
//创建新目录
String uri = File.separator + DateUtil.getNowDateStr(File.separator);
File dir = new File(localPath + uri);
if(!dir.exists()){
dir.mkdirs();
}
//创建新文件
String newFileName = StringUtil.getUniqueFileName();
File f = new File(dir.getPath() + File.separator + newFileName + "." + suffix);
//将输入流中的数据复制到新文件
FileUtils.copyInputStreamToFile(file.getInputStream(), f);
String Url = (urlPath + uri.replace("\\", "/") + newFileName + "." + suffix);
//插入到数据库
//...
params.put("resultStr", Url);
return true;
}