springboot实现图片上传之代码(一)

1结构

 2在js中新建upload.html

<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<title>uploading.html</title>
<meta name="keywords" content="keyword1,keywords2,keywords3"/>
<meta http-equiv="Content-Type" content="text/html;charset=utf-8"/>
</head>
<body>
<form enctype="multipart/form-data" method="post" action="/upload">
文件:<input type="file" name="head_img"/><br>
姓名:<input type="text" name="name"/>
<input type="submit" value="上传"/>
</form>
</body>
</html>

3新建一个数据处理类JsonDate

package com.example.demo.domian;

import java.io.Serializable;

public class JsonData implements Serializable{

private static final long seriaVersionUID=1L;

//状态码,0表示成功,-1表示失败
private int code;

//结果
private Object data;

//返回错误消息
private String msg;

public int getCode() {
return code;
}

public void setCode(int code) {
this.code = code;
}

public Object getData() {
return data;
}

public void setData(Object data) {
this.data = data;
}

public String getMsg() {
return msg;
}

public void setMsg(String msg) {
this.msg = msg;
}

public JsonData(int code, Object data, String msg) {
super();
this.code = code;
this.data = data;
this.msg = msg;
}




}

4在controller中新建一个fileController,加入以下代码

/**
* 文件存储路径,可以自定义,我存到的是项目中的image中
* 登陆地址:localhost:8080/js/upload.html
*/
private static final String filePath="G:\study_tool\maven_workspace\demo\src\main\resources\static\image\";
/**
* MultipartFile对象的transferTo的效率和操作要比原先的FileOutStream方便和高效
* @param file
* @param request
* @return
*/
@RequestMapping(value="upload")
@ResponseBody
public JsonData upload(@RequestParam("head_img")MultipartFile file,HttpServletRequest request) {

//获取用户名
String name=request.getParameter("name");
System.out.println("用户名:"+name);

//获取文件名
String fileName=file.getOriginalFilename();
System.out.println("上传的文件名为:"+fileName);

//获取文件的后缀
String suffixName=fileName.substring(fileName.lastIndexOf("."));
System.out.println("上传的后缀名为:"+suffixName);

//文件上传前的路径
fileName=UUID.randomUUID()+suffixName;
System.out.println("上传前的文件:"+fileName);

File dest=new File(filePath+fileName);
try {
file.transferTo(dest);
return new JsonData(0,fileName,null);
}catch(IOException e) {
e.printStackTrace();
}catch(IllegalStateException e) {
e.printStackTrace();
}

return new JsonData(-1,"file save faile",null);

}

5访问地址:localhost:8080/js/upload.html   上传文件,页面会跳转

然后复制图片的名字,通过lhttp://localhost:8080/image/d1bd9aa2-800f-446b-a483-1a0f6dd9fd07.jpg即可访问

原文地址:https://www.cnblogs.com/zhushilai/p/13501609.html