1200字范文,内容丰富有趣,写作的好帮手!
1200字范文 > ssm框架结合Ajax实现图片上传功能

ssm框架结合Ajax实现图片上传功能

时间:2021-05-05 19:17:35

相关推荐

ssm框架结合Ajax实现图片上传功能

先上代码

一.html代码

<div><img src="img/头像.png" alt="选择并上传头像" id="avatar_img" style="width: 100px;height: 100px;left:0;top: 0;"/><input type="file" id="avatar_file" name="avatar_file"accept="image/jpg,image/png,image/gif"style="width: 100%;height: 100px;opacity: 0;position: absolute;left:0px;top: 0;"/></div>

二.js代码

// 头像预览$("#avatar_file").change(function () {// 获取上传文件对象var file = $(this)[0].files[0];// 读取文件URLvar reader = new FileReader();reader.readAsDataURL(file);// 阅读文件完成后触发的事件reader.onload = function () {// 读取的URL结果:this.result$("#avatar_img").attr("src", this.result);var formFile = new FormData();formFile.append("user_id",window.location.search.substr(1));formFile.append("file",file);var data = formFile;$.ajax({url : 'http://localhost:8080/addUserPicture',type : 'post',dataType : 'json',data : data,cache: false, //上传文件无需缓存processData: false, // 用于对参数进行序列化处理,这里必须设为falsecontentType:false, // 必须success : function(data) {console.log(data);if (data.state == 200) {alert("图片上传成功!")}if(data.state == 300){alert("图片上传失败!");return;}},})}})$.ajax({url:"http://localhost:8080/showUserPicture?user_id="+userid,type:"post",success:function(result){var src = "http://localhost:8080/"+result$("#avatar_img").attr("src",src);}})

三.后端代码

1.两个工具类

package com.bzw.util;import java.io.Serializable;/**

JsonResult工具类

* 用于封装服务器到客户端的Json返回值** @author soft01**/public class JsonResult<T> implements Serializable {// Serializable将对象的状态保存在存储媒体中以便可以在以后重新创建出完全相同的副本public static final int SUCCESS = 0;public static final int ERROR = 1;public static final int OTHER = 2;private int state;private String message = "";private T data;private String pass = "";public JsonResult() {state = SUCCESS;}// 为了方便,重载n个构造器public JsonResult(int state, String message, T data) {super();this.state = state;this.message = message;this.data = data;}public JsonResult(int state, String error) {this(state, error, null);}public JsonResult(int state, T data) {this(state, "", data);}public JsonResult(String error) {this(ERROR, error, null);}public JsonResult(T data) {this(SUCCESS, "", data);}public JsonResult(int state) {this(state, "", null);}public JsonResult(Throwable e) {this(ERROR, e.getMessage(), null);}public int getState() {return state;}public void setState(int state) {this.state = state;}public String getMessage() {return message;}public void setMessage(String message) {this.message = message;}public T getData() {return data;}public void setData(T data) {this.data = data;}public static int getSuccess() {return SUCCESS;}public static int getError() {return ERROR;}@Overridepublic String toString() {return "JsonResult [state=" + state + ", message=" + message+ ", pass=" + pass + ", data=" + data + "]";}}

# UploadUtil工具类。使用UUID防止图片名称以及图片路径重复

package com.bzw.util;

import mons.io.FilenameUtils;

import org.springframework.web.bind.annotation.RequestParam;

import org.springframework.web.multipart.MultipartFile;

import javax.servlet.http.HttpServletRequest;

import java.io.File;

import java.io.IOException;

import java.util.UUID;

public class UploadUtil {

public static String imageUpload(@RequestParam(value="file") MultipartFile file, HttpServletRequest req){

// 获取要上传的目标位置,即是项目的upload文件夹所在的绝对路径

//如果添加了tomcat的虚拟映射路径,需要先新建一个upload文件夹

String path = req.getSession().getServletContext().getRealPath("upload");

// 获取文件的扩展名

String ext = FilenameUtils.getExtension(file.getOriginalFilename());

String filename = UUID.randomUUID().toString().replaceAll("-", "")+"."+ ext;

// 写入文件成功之后,返回的数据,也就是数据库里要存的文件的url

String src="upload/"+filename;

File targetFile= new File(path,filename);

try {

if(!targetFile.exists()){

//写入文件

file.transferTo(targetFile);

return src;

}

} catch (IllegalStateException e) {

e.printStackTrace();

} catch (IOException e) {

e.printStackTrace();

}

//写入文件失败,则返回空字符串

return "";

}

}

2.controller

@PostMapping("/addUserPicture")public JsonResult<String> insertPicture(@RequestParam(value = "file") MultipartFile pictureFile, HttpServletRequest request,@RequestParam(value = "user_id") int userid){// pictureURL是数据库里picture_url的值,这里用到一个封装的工具类UploadUtilString pictureURL = UploadUtil.imageUpload(pictureFile, request);System.out.println("pictureURL:" + pictureURL);//获取上传时的文件名String pictureName = FilenameUtils.getName(pictureFile.getOriginalFilename());System.out.println("pictureName:" + pictureName);// 把图片数据保存到数据库User user = new User();//暂时将user_tel,user_email存放图片名称和路径user.setUser_tel(pictureName);user.setUser_email(pictureURL);try {userService.updateUser(user,userid);return new JsonResult<>(200, "上传成功!", user.getUser_email());} catch (Exception e) {return new JsonResult<>(300, "上传失败", null);}}@PostMapping("/showUserPicture")public String showUserPicture(@RequestParam(value = "user_id") int userId){User user = new User();try {user = userService.selectUser(userId);} catch (Exception e) {e.printStackTrace();}return user.getUser_email();}

值得注意的地方:

1.我使用的是IDEA,要在target目录下手动创建一个upload文件夹,否则会找不到文件路径。

2.前端访问图片路径是 服务器端口号+图片相对路径

参考博客:

/linmengmeng_1314/article/details/84944056

本内容不代表本网观点和政治立场,如有侵犯你的权益请联系我们处理。
网友评论
网友评论仅供其表达个人看法,并不表明网站立场。