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即可訪問

 

 


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM