使用SpringMVC的MultipartFile文件
HMTL页面
<body>
<form enctype="multipart/form-data" method="post" action="/upload">
图片:<input type="file" name="pic_img"/>
说明:<input type="text" name="name"/>
<input type="submit" value="上传"/>
</form>
</body>
Controller页面
@Controller
public class UploadController {
/**
*
* @param file
* @param request 请求对象
* @return 返回JSON对象
*/
@RequestMapping("/upload")
@ResponseBody
public JsonData upload(@RequestParam("pic_img") MultipartFile file, HttpServletRequest request){
//获得说明参数
String name = request.getParameter("name");
System.out.println("name="+name);
//获得文件参数
String fileName = file.getOriginalFilename();
System.out.println("上传的文件名fileName="+fileName);
//获取文件的后缀名 .jpeg,jpg,png,gif...
String stuffixName =fileName.substring(fileName.lastIndexOf("."));
System.out.println("上传的后缀名="+stuffixName);
//重新生成文件名+后缀名
fileName= UUID.randomUUID()+stuffixName;
//文件存放的路径/
File filePath = null;
try {
//获得当前工程路径F:\newdemo\target\classes\
File path = new File(ResourceUtils.getURL("classpath:").getPath());
//图片需要存放的路径F:\newdemo\target\classes\static\images
filePath = new File(path.getAbsolutePath(), "static/images/");
System.out.println("上传文件路径:"+filePath);
} catch (FileNotFoundException e) {
e.printStackTrace();
}
//
//文件上传的路径
File desc=new File (filePath+"/"+fileName);
System.out.println(desc);
try {
//用于文件保存(效率和操作比原先用FileOutStream方便和高效)
file.transferTo(desc);
//上传OK
return new JsonData(0,desc);
} catch (IOException e) {
e.printStackTrace();
}
//错误消息
return new JsonData(-1,"file upload is not fail!!");
}
}
JsonData类保存JSON
**
* 返回到的一个结果封装
*/
public class JsonData implements Serializable {
//状态码 0表示OK,1表示No;
private int id;
//结果
private Object result ;
public JsonData(int id, String msg) {
this.id = id;
this.msg = msg;
}
//错误消息
private String msg;
public String getMsg() {
return msg;
}
public void setMsg(String msg) {
this.msg = msg;
}
public JsonData() {
}
public JsonData(int id, Object result) {
this.id = id;
this.result = result;
}
public int getId() {
return id;
}
public void setId(int id) {
this.id = id;
}
public Object getResult() {
return result;
}
public void setResult(Object result) {
this.result = result;
}
public JsonData(int id, Object result, String msg) {
this.id = id;
this.result = result;
this.msg = msg;
}
}
运行效果:
访问路径 http://localhost:8080/images/图片名称
如果传入大图片时,就会发生异常哦!
那如何解决呢?
在NewdemoApplication类中添加以下代码:
@Bean
public MultipartConfigElement multipartConfigElement() {
MultipartConfigFactory factory = new MultipartConfigFactory();
//单个文件最大10M
factory.setMaxFileSize("10240KB"); //KB,MB
/// 设置总上传数据总大小 1000M
factory.setMaxRequestSize("1024000KB");
return factory.createMultipartConfig();
}
再运行:
上传后的大图片