首先,欢迎各位能观看这篇文章,今天给各位介绍如何使用前端uniapp技术进行上传图片到服务器数据库中!

在这里插入图片描述

一 ,从以下几点进行阐述功能

1,前端用的什么框架?

  • 前端技术用的uniapp框架,ajax请求服务器ip地址,访问后台提供的接口,上传到服务器,服务器接受到存储到数据库;

2.后台用的什么编写?

  • 后台主要以eclipse进行编程,主要负责逻辑的功能,提供有效的接口给前端者,处理好与服务器数据库的连接,以及存储到服务器的路径地址;

3.我们要做到什么样的功能?

  • 能够前端访问https:xxxxxxx,利用ajax请求上传图片到服务器,服务器进行存储到本地创建的文件夹目录下并有效的进行查看

具体逻辑分析点如下:

  1. 前端编写form层,必须要使用enctype=“multipart/form-data”,写入一个点击弹出选择图片的文件目录功能,如input控件
  2. ajax请求上传的函数
  3. eclipse后台逻辑的编写,先判断接收到前端开发者发送过来的请求体
  4. 再进入上传图片的函数,配置上传参数
  5. 设置临时目录,如果有就不创建,没有就创建
  6. 设置文件的最大值和文件请求的最大值
  7. 存储到服务器的路径地址url
  8. 处理解析文件的数据
  9. 判断上传过来的图片名,在数据库中是否已经存在,如果存在就直接提示上传失败
  10. 通过ID查询数据库表是否有相同的图片名
  11. 如果不相同的图片名,就进入到添加服务器数据库的函数
  12. 编写类的实体类,数据库的设计逻辑
  13. 设置路径后面+图片名
  14. 通过查找数据库表
  15. 成功添加后进行返回到主体判断的函数
  16. 把此链接添加到数据库表,并构造一个JSON数据返回给前端用户

二:编码区

1,前端代码

<form method="post"  enctype="multipart/form-data">
	<input type="submit" @click="upload" value="选择照片"/>
</form>

ajax请求体

upload: function() {
	_self = this;

	uni.chooseImage({
		count: _self.connent_index,
		sizeType: ['original', 'compressed'], //可以指定是原图还是压缩图,默认二者都有
		sourceType: ['camera','album'], //从相册选择
		success: function(res) {
			const tempFilePaths = res.tempFiles;
			console.log("code++:"+JSON.stringify(tempFilePaths))
		for (var i = 0; i < tempFilePaths.length; i++) {

			const uploadTask = uni.uploadFile({
				url: 'http://47.xxx.xxx.xxx:8090/YYCJH/RishengMain?action=Uploadmage',
				filePath: tempFilePaths[i].path,
				name: 'file',
				success: function(uploadFileRes) {
					console.log('已经上传的数据长度' + uploadFileRes.data);
					let base64 = 'data:image/jpeg;base64,' + uploadFileRes.data;
					console.log('已经上传的数据长度' + base64);
				}
			});
			uploadTask.onProgressUpdate(function(res) {
				console.log('已经上传的数据长度' + res.totalBytesSent);
				console.log('预期需要上传的数据总长度' + res.totalBytesExpectedToSend);
			});
		}	
		},
		error: function(e) {
			console.log(e);
		}
	});
}

2.eclipse后台编写如下:

  • 主方法请求体
protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {

	response.setContentType("text/html;charset=utf-8");
	request.setCharacterEncoding("utf-8");
	response.setCharacterEncoding("utf-8");
	response.setHeader("Access-Control-Allow-Origin", "*");
	
	String actionString = request.getParameter("action");

if(actionString.equals("Uploadmage")) {
     	UploadImageDate(request, response);
     }
}
  • 上传的函数UploadImageDate
//上传的函数方法
	protected void UploadImageDate(HttpServletRequest request, HttpServletResponse response)throws ServletException, IOException {

// 检测是否为多媒体上传
        if (!ServletFileUpload.isMultipartContent(request)) {
            // 如果不是则停止
            PrintWriter writer = response.getWriter();
            writer.println("Error: 表单必须包含 enctype=multipart/form-data");
            writer.flush();
            return;
        }
        
        // 配置上传参数
        DiskFileItemFactory factory = new DiskFileItemFactory();
        // 设置内存临界值 - 超过后将产生临时文件并存储于临时目录中
        factory.setSizeThreshold(MEMORY_THRESHOLD);
        // 设置临时存储目录
        factory.setRepository(new File(System.getProperty("java.io.tmpdir")));
 
        ServletFileUpload upload = new ServletFileUpload(factory);
         
        // 设置最大文件上传值
        upload.setFileSizeMax(MAX_FILE_SIZE);
         
        // 设置最大请求值 (包含文件和表单数据)
        upload.setSizeMax(MAX_REQUEST_SIZE);

        // 中文处理
        upload.setHeaderEncoding("UTF-8"); 

 String uploadPath = "C:\\Users\\Administrator\\Desktop\\image\\upload\\";
         
        // 如果目录不存在则创建
        File uploadDir = new File(uploadPath);
        if (!uploadDir.exists()) {
            uploadDir.mkdir();
        }
        
        try {
            // 解析请求的内容提取文件数据
        	 @SuppressWarnings("unchecked")
            List<FileItem> formItems = upload.parseRequest(request);
          
            if (formItems != null && formItems.size() > 0) {
                // 迭代表单数据
                for (FileItem item : formItems) {
                    // 处理不在表单中的字段
                    if (!item.isFormField()) {
                        String fileName = new File(item.getName()).getName();

                        String filePath = uploadPath + fileName;
                        File storeFile = new File(filePath);
                        
                        //判断数据库中的图片名是否有相同的
                        boolean checkname = ImageUserHelp.CheckImageName(fileName);
                        
                        if(checkname) {
                        	//添加到数据库
    						if(jsonString != null) {
    						    jsonString = AddImageToSqlDate(fileName, filePath);
    							ResponseUtils.renderJson(response, jsonString);
    							
    							//在控制台输出文件的上传路径
    	                        System.out.println(filePath);
    	                        // 保存文件到硬盘
    	                        item.write(storeFile);
    						}else {
    							String responseText = "{\"code\":\"00112\",\"msg\":\"访问错误\",\"items\":[]}";
    							ResponseUtils.renderJson(response, responseText); 
    						}
                        }else {
                        	String responseText = "{\"code\":\"00112\",\"msg\":\"访问错误\",\"items\":[]}";
							ResponseUtils.renderJson(response, responseText); 
                        }
                    }
                }
            }
        } catch (Exception ex) {
            request.setAttribute("message",
                    "错误信息: " + ex.getMessage());
        }

}
  • AddImageToSqlDate
	/**
	 * 添加图片到数据库LoginUser
	 * **/
	private String AddImageToSqlDate(String name,String picturepath) {
		return UserBeanHelp.AddImageUserBean(name,picturepath);
	}
  • ImageUserHelp
public class ImageUserHelp {

	private static ImageUserUtil ulogin;
	private static String jsonString;
	private static List<Picture> meslist = new ArrayList<>();
	
	public static String InterfaceImageBean() throws SQLException{

		ulogin = new ImageUserUtil();
		
		try {

		meslist = ulogin.interfaceImageBean();
		
		if(meslist != null){
			//数据库返回过来的列表
			if(meslist.size()<0){
				ListObject listObject=new ListObject();
				listObject.setItems("");
				listObject.setStatusObject(StatusHouse.COMMON_STATUS_ERROR);
				jsonString = JackJsonUtils.toJson(listObject);

			}else{
				ListObject listObject=new ListObject();
				listObject.setItems(meslist);
				listObject.setStatusObject(StatusHouse.COMMON_STATUS_OK);
				jsonString = JackJsonUtils.toJson(listObject);
				
			}
		}else {
			ListObject listObject=new ListObject();
			listObject.setItems("");
			listObject.setStatusObject(StatusHouse.COMMON_STATUS_ERROR);
			jsonString = JackJsonUtils.toJson(listObject);
		}
		} catch (SQLException e1) {
			e1.printStackTrace();
		}
		return jsonString;
	}
	
	
	/**
	 * 检查数据库中的图片名是否相同
	 * @param userName
	 * @return
	 */
	public static boolean CheckImageName(String imageName){
		try{
			ulogin = new ImageUserUtil();
			int a = ulogin.queryImageName(imageName);
			if(a<=0){
				return true;
			}

		}catch (Exception e) {
			e.printStackTrace();
		}
		
		return false;
		
	}
}
  • ImageUserUtil
public class ImageUserUtil implements ImageDao{

	/*
	 * 消息接口interfaceMessageBean
	 * (UserBean user) throws SQLException
	 */

	@Override
	public List<Picture> interfaceImageBean() throws SQLException {
		List<Picture> lista = new ArrayList<Picture>();

		String sql = null;
		MysqlinstallDb db1 = null;
		sql = "select * from UploadImageCode";
		db1 = new MysqlinstallDb(sql);//
		ResultSet ret = null;
		Connection conn = MysqlinstallDb.getConnection();
		PreparedStatement ps = conn.prepareStatement(sql);
	
		try{
			ret = db1.pst.executeQuery();
			while (ret.next()) {
				Picture ub = new Picture();
				ub.setId(ret.getInt("id"));
				ub.setName(ret.getString("name"));
				ub.setPicturepath(ret.getString("picturepath"));
				lista.add(ub);
				
			}
			
			MysqlinstallDb.fastcloseStmt(ps);
			MysqlinstallDb.closeConnection(conn);
		}catch (Exception e) {
			e.printStackTrace();
			
		}
		return lista;
	}
	
	
	/**
	 * 查询账号是否有相同的用户名
	 */
	@Override
	public int queryImageName(String imageName){
	
		String sql = null;
		MysqlinstallDb db1 = null;
		sql = "select * from uploadimagecode where name="+"'"+imageName+"'";
		db1 = new MysqlinstallDb(sql);//
		ResultSet ret = null;
		int like = 0;
	
		try{
			ret = db1.pst.executeQuery();
			ret.next();
			like = ret.getInt("id");
			if(like<=0){
				return 0;
			}else{
				return 1;
			}
			
			
			
		}catch (Exception e) {
			//e.printStackTrace();
			like = 0;
		}
		return like;
	}
}
  • UserBeanHelp
	/**
	 * 添加图片接口的回调
	 * **/
	
	public static String AddImageUserBean(String name,String picturepath) {

		ubu = new UserBeanUtil();
		try {
			Picture user = new Picture();
			user.setName(name);
			user.setPicturepath("http://47.xxx.xxx.xxx:8090\\upload\\"+name);
			
			listImage = ubu.insertAddImageUserBean(user);
			
			if(listImage != null) {
				//数据库返回过来的列表
				if(listImage.size()<0){
					ListObject listObject=new ListObject();
					listObject.setItems("");
					listObject.setStatusObject(StatusHouse.COMMON_STATUS_ERROR);
					jsonString = JackJsonUtils.toJson(listObject);

				}else{
					ListObject listObject=new ListObject();
					listObject.setItems(listImage);
					listObject.setStatusObject(StatusHouse.COMMON_STATUS_OK);
					jsonString = JackJsonUtils.toJson(listObject);
					
				}
			}else {
				ListObject listObject=new ListObject();
				listObject.setItems("");
				listObject.setStatusObject(StatusHouse.COMMON_STATUS_ERROR);
				jsonString = JackJsonUtils.toJson(listObject);
			}


		} catch (SQLException e1) {
			e1.printStackTrace();
		}

		return jsonString;
	}
  • UserBeanUtil
public class UserBeanHelp {

	private static UserBeanUtil ubu;
	private static String jsonString;
	private static List<Picture> listImage = new ArrayList<>();
	
	}

	/**
	 * 图片
	 * **/
	@Override
	public List<Picture> insertAddImageUserBean(Picture user) throws SQLException {
		List<Picture> listimg = new ArrayList<Picture>();
		String sql="insert into UploadImageCode(name,picturepath) values(?,?)";
	
		try{
			Connection conn = MysqlinstallDb.getConnection();
			PreparedStatement ps = conn.prepareStatement(sql);
			ps.setString(1, user.getName());
			ps.setString(2, user.getPicturepath());
			
			int rows = ps.executeUpdate();
			System.out.println("rows");
			if(rows>0){
				String sql1="select * from UploadImageCode where name="+"'"+user.getName()+"'"+" and picturepath="+"'"+user.getPicturepath()+"'";
				Statement stmt = conn.createStatement();
				ResultSet rs = stmt.executeQuery(sql1);
				while (rs.next()) {
					Picture ub = new Picture();
					ub.setName(rs.getString("name"));
					ub.setPicturepath(rs.getString("picturepath"));
					listimg.add(ub);
				}
				
				System.out.println("成功添加了"+rows+"条数据!");
				return listimg;
			}
			MysqlinstallDb.fastcloseStmt(ps);
			MysqlinstallDb.closeConnection(conn);
			
		}catch (Exception e) {
			e.printStackTrace();
		}
		
		return null;
	}
  • Picture
public class Picture {
	private String name;
	private String picturepath;
	private int id;
	
	public String getName() {
		return name;
	}
	
	public String getPicturepath() {
		return picturepath;
	}
	
	
	public int getId() {
		return id;
	}
	
	public void setName(String name) {
		this.name = name;
	}
	
	public void setPicturepath(String picturepath) {
		this.picturepath = picturepath;
	}
	
	public void setId(int id) {
		this.id = id;
	}
	
}
  • MysqlinstallDb
public class MysqlinstallDb {

	public static final String url = "jdbc:mysql://localhost:3306/userLoginRegistion?useSSL=false&serverTimezone=UTC";  
    public static final String name = "com.mysql.cj.jdbc.Driver";  
    public static final String user = "root";  
    public static final String password = "123456";  
  
    public Connection conn = null;  
    public PreparedStatement pst = null;  
  
    public MysqlinstallDb(String sql) {  
        try {
            Class.forName(name);//
            conn = DriverManager.getConnection(url, user, password);//
            pst = conn.prepareStatement(sql);//
        } catch (Exception e) { 
        	System.out.println("inita [SQL驱动程序初始化失败!]");
            e.printStackTrace();
        }  
    } 
    }
  • UserDao
public interface UserDao {
    
	/**
     * 添加图片接口
     * @param user
     * @return
     * @throws SQLException
     */
    public List<Picture> insertAddImageUserBean(Picture user) throws SQLException;

    
    /** 
     * 查询数据库中是否有对应的UserName,如果有,返回对应id,没有,返回0 
     *  
     * @param connection 
     * @param userName 
     * @return 
     */  
    public int queryUserName(String userName) throws SQLException; 

}

三:图片展示

1
在这里插入图片描述
2
在这里插入图片描述
3
在这里插入图片描述
4
在这里插入图片描述
5.完毕!谢谢!

更多推荐