1、静态文件
<!DOCTYPE html> <html> <head> <meta charset="UTF-8"> <title>文件上传</title> </head> <body> <form enctype="multipart/form-data" method="post" action="/v1/upload"> 文件:<input type="file" name="fileName"/></br></br> 备注:<input type="text" name="remark"/> <input type="submit" value="上传"/> </form> </body> </html>
2、return result
package cn.xiaobing.demo.pojo; public class Result { 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 Result(int code, Object data, String msg) { super(); this.code = code; this.data = data; this.msg = msg; } public Result() { super(); } @Override public String toString() { return "Result [code=" + code + ", data=" + data + ", msg=" + msg + "]"; } }
3、FileController
package cn.xiaobing.demo.controller; import java.io.File; import java.util.HashMap; import java.util.Map; import java.util.UUID; import javax.servlet.http.HttpServletRequest; import org.springframework.stereotype.Controller; import org.springframework.web.bind.annotation.RequestMapping; import org.springframework.web.bind.annotation.RequestParam; import org.springframework.web.bind.annotation.ResponseBody; import org.springframework.web.multipart.MultipartFile; import cn.xiaobing.demo.pojo.Result; @Controller public class FileController { private static final String filePath = "C:/oneself/eclipse-workspace/springboot-v0/src/main/resources/static/images"; @RequestMapping(value="/v1/upload") @ResponseBody public Object upload(@RequestParam("fileName") MultipartFile file,HttpServletRequest request) { String remark = request.getParameter("remark");//备注信息 String filename = file.getOriginalFilename();//获取文件名称 String suffixname = filename.substring(filename.lastIndexOf("."));//后缀 filename = UUID.randomUUID() + suffixname;//文件上传后重命名数据库存储 File dest = new File(filePath,filename); Map<String, String> data = new HashMap<String, String>(); data.put("filename", filename); data.put("备注 ", remark); try { file.transferTo(dest);//拷贝文件到指定路径储存 return new Result(0, data, "上传成功"); } catch (Exception e) { e.printStackTrace(); return new Result(-1, data, "上传失败"); } } }
4、启动项目
. ____ _ __ _ _ /\\ / ___'_ __ _ _(_)_ __ __ _ \ \ \ \ ( ( )\___ | '_ | '_| | '_ \/ _` | \ \ \ \ \\/ ___)| |_)| | | | | || (_| | ) ) ) ) ' |____| .__|_| |_|_| |_\__, | / / / / =========|_|==============|___/=/_/_/_/ :: Spring Boot :: (v2.0.1.RELEASE)
5、访问upload.html上传文件
6、点击上传,上传文件成功
7、点击上传,上传失败
8、不足之处,后续优化。。。