java后台加安卓端实现头像上传功能

1、手机上传压缩后的图片到服务器

2、后台接收到图片进行图片重命名、保存


后台代码

          

package service;


import java.io.File;
import java.io.IOException;
import java.util.List;


import javax.servlet.Servlet;
import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;


import org.apache.commons.fileupload.FileItem;
import org.apache.commons.fileupload.FileUploadException;
import org.apache.commons.fileupload.disk.DiskFileItemFactory;
import org.apache.commons.fileupload.servlet.ServletFileUpload;


import bean.UpdateHeadBean;
import net.sf.json.JSONObject;
import utils.DbUtil;


@WebServlet("/UpdateHead")
public class UpdateHead extends HttpServlet implements Servlet{
private static final long serialVersionUID = 1L;
    public UpdateHead() {
    super();
    }
protected void doGet(HttpServletRequest request, HttpServletResponse response) throws 
ServletException, IOException {
this.doPost(request, response);
response.getWriter().append("Served at: ").append(request.getContextPath());
}
protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, 
IOException {
  response.setCharacterEncoding("UTF-8");
DiskFileItemFactory factory = new DiskFileItemFactory();
ServletFileUpload upload = new ServletFileUpload(factory);
List<FileItem> items;
UpdateHeadBean updateHeadBean = new UpdateHeadBean();
try {
int uId = 0;
String pic =null;
String headName = null;
items = upload.parseRequest(request);//参数是HttpServletRequest对象
for (FileItem item : items){//遍历所有客户端提交的参数(包括文件域)
if(item.isFormField()){
if("uPic".equals(item.getFieldName())){//获取手机端传的参数(用户id)
uId=Integer.valueOf(item.getString());
 pic = DbUtil.queryPic(uId);
System.out.println("value:"+item.getString());
}
}else{
String key = item.getFieldName();//取出文件域的键
      String value = item.getName();//取出文件域的值
      long fileLen = item.getSize();//取出上传文件的尺寸
      String mimeType = item.getContentType();//取出上传文件的类型
      File f=new File("D:\\test\\");//文件地址(上传后服务器硬盘地址)
      f.mkdirs();
       headName = System.currentTimeMillis()+value.substring(value.indexOf("."),value.length());
      //保存图片到服务器
       item.write(new File(f+"\\"+headName));//保存上传的文件到服务器本地
      
      System.out.println("value:"+headName);
}
updateHeadBean.setStatus(0);
updateHeadBean.setMsg("上传成功");
}
//根据用户id保存图片名称到数据库
  DbUtil.saveHead(headName, uId);
  //删除原来的图片文件
  if(pic!=null&&pic!="1520848305600.jpg"){
       File file = new File("d:\\test\\"+pic);
       try {
         if (file.exists()) {// 上面文件创建,已存在就删除
             boolean d = file.delete();
         }
       } catch (Exception e) {
           e.printStackTrace();
       }
  }
} catch (Exception e) {
updateHeadBean.setStatus(1);
updateHeadBean.setMsg("上传失败");
e.printStackTrace();
}
//实体类转为json字符串返回给客户端
    JSONObject msg = JSONObject.fromObject(updateHeadBean);
    response.getWriter().write(msg.toString());

}

}

数据库操作类

package utils;


import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.sql.Statement;


import bean.Student;


public class DbUtil {
/*
* 保存数据
*/
public static Object saveData(String name,int age,String pss){
Connection connection = null;
        PreparedStatement preparedStatement = null;
        ResultSet rs = null;  
        Object retId = null; 
        try{
        // 获取连接
        connection = JdbcUtils.getConnection();
        // 准备sql语句
        String sql = "INSERT INTO students(name,age,pss) VALUES(?,?,?)";
        // 获取PrepareStatement对象
        preparedStatement = connection.prepareStatement(sql,Statement.RETURN_GENERATED_KEYS);
            // 填充占位符
            preparedStatement.setString(1, name);
            preparedStatement.setInt(2, age);
            preparedStatement.setString(3, pss);
            // 执行sql
           preparedStatement.executeUpdate();
           rs = preparedStatement.getGeneratedKeys();
           if (rs.next()){ 
          retId = rs.getObject(1);}  
           return retId;
        }catch(SQLException  e){
        e.printStackTrace();
        return null;
        }finally{
        JdbcUtils.releaseDB(connection, preparedStatement, null);
        }
}
/*
* 查询数据
*/
public static String queryData(String name){
Connection connection = null;
ResultSet rs = null;
        try{
        // 获取连接
        connection = JdbcUtils.getConnection();
        Statement statement = connection.createStatement();
         rs=statement.executeQuery("select * from students where name='"+name+"'");
        if(rs.next()){
         String userName = rs.getString("name");
         return "注册成功!";
        }
        }catch(SQLException  e){
        e.printStackTrace();
        return "错误!";
        }
        finally{
        try {
connection.close();
rs.close();
} catch (SQLException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
        }
        return "错误!";
}
/*
* 查询数据
*/
public static String queryPic(int id){
Connection connection = null;
ResultSet rs = null;
        try{
        // 获取连接
        connection = JdbcUtils.getConnection();
        Statement statement = connection.createStatement();
         rs=statement.executeQuery("select * from students where id='"+id+"'");
        if(rs.next()){
         String pic = rs.getString("pic");
         return pic;
        }
        }catch(SQLException  e){
        e.printStackTrace();
        return null;
        }
        finally{
        try {
connection.close();
rs.close();
} catch (SQLException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
        }
        return null;
}
public static Object queryData(String name,String pss,boolean flag){
Connection connection = null;
ResultSet rs = null;
        try{
        // 获取连接
        connection = JdbcUtils.getConnection();
        Statement statement = connection.createStatement();
         rs=statement.executeQuery("select * from students where name='"+name+"'and pss ='"+pss+"'");
        if(rs.next()){
        Object msg;
        if(flag){
        msg = rs.getInt("id");
        }else{
        msg = rs.getString("pic");
        }
         return msg;
        }
        }catch(SQLException  e){
        e.printStackTrace();
        return null;
        }
        finally{
        try {
connection.close();
rs.close();
} catch (SQLException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
        }
        return null;
}
/**
* 保存上传的头像
*/
public static boolean saveHead(String picName,int id){
Connection connection = null;
        PreparedStatement preparedStatement = null;
        try{
        // 获取连接
        connection = JdbcUtils.getConnection();
        // 准备sql语句  UPDATE Person SET FirstName = 'Fred' WHERE LastName = 'Wilson' 
        String sql = "update students set pic=? where id='"+id+"'";
        // 获取PrepareStatement对象
        preparedStatement = connection.prepareStatement(sql,Statement.RETURN_GENERATED_KEYS);
            // 填充占位符
            preparedStatement.setString(1, picName);
            // 执行sql
           preparedStatement.execute();
           return true;
        }catch(SQLException  e){
        e.printStackTrace();
        return false;
        }finally{
        JdbcUtils.releaseDB(connection, preparedStatement, null);
        }
}


}

3、使用tomcat映射图片地址

打开Tomcat安装文件夹——>conf——>Catalina——>localhost

创建xml文件 pic.xml (文件名必须与Context path的值一致),docBase与workDir的值为图片所在文件夹,配置好后可在浏览器通过192.168.0.101:8080/pic/文件名 访问图片(192.168.0.101:8080为本机ip与tomcat端口号)

<?xml version="1.0" encoding="UTF-8"?>
<Context path="/pic" 
docBase="D:/test" 
workDir="D:/test" 
debug="0" 
reloadable="true" 
crossContext="true" />

阅读更多
想对作者说点什么? 我来说一句

没有更多推荐了,返回首页

关闭
关闭
关闭