app上传头像处理Java_java后台加安卓端实现头像上传功能
1、手機(jī)上傳壓縮后的圖片到服務(wù)器
2、后臺(tái)接收到圖片進(jìn)行圖片重命名、保存
后臺(tái)代碼
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 items;
UpdateHeadBean updateHeadBean = new UpdateHeadBean();
try {
int uId = 0;
String pic =null;
String headName = null;
items = upload.parseRequest(request);//參數(shù)是HttpServletRequest對(duì)象
for (FileItem item : items){//遍歷所有客戶端提交的參數(shù)(包括文件域)
if(item.isFormField()){
if("uPic".equals(item.getFieldName())){//獲取手機(jī)端傳的參數(shù)(用戶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();//取出上傳文件的類(lèi)型
File f=new File("D:\\test\\");//文件地址(上傳后服務(wù)器硬盤(pán)地址)
f.mkdirs();
headName = System.currentTimeMillis()+value.substring(value.indexOf("."),value.length());
//保存圖片到服務(wù)器
item.write(new File(f+"\\"+headName));//保存上傳的文件到服務(wù)器本地
System.out.println("value:"+headName);
}
updateHeadBean.setStatus(0);
updateHeadBean.setMsg("上傳成功");
}
//根據(jù)用戶id保存圖片名稱(chēng)到數(shù)據(jù)庫(kù)
DbUtil.saveHead(headName, uId);
//刪除原來(lái)的圖片文件
if(pic!=null&&pic!="1520848305600.jpg"){
File file = new File("d:\\test\\"+pic);
try {
if (file.exists()) {// 上面文件創(chuàng)建,已存在就刪除
boolean d = file.delete();
}
} catch (Exception e) {
e.printStackTrace();
}
}
} catch (Exception e) {
updateHeadBean.setStatus(1);
updateHeadBean.setMsg("上傳失敗");
e.printStackTrace();
}
//實(shí)體類(lèi)轉(zhuǎn)為json字符串返回給客戶端
JSONObject msg = JSONObject.fromObject(updateHeadBean);
response.getWriter().write(msg.toString());
}
}
數(shù)據(jù)庫(kù)操作類(lèi)
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 {
/*
* 保存數(shù)據(jù)
*/
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();
// 準(zhǔn)備sql語(yǔ)句
String sql = "INSERT INTO students(name,age,pss) VALUES(?,?,?)";
// 獲取PrepareStatement對(duì)象
preparedStatement = connection.prepareStatement(sql,Statement.RETURN_GENERATED_KEYS);
// 填充占位符
preparedStatement.setString(1, name);
preparedStatement.setInt(2, age);
preparedStatement.setString(3, pss);
// 執(zhí)行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);
}
}
/*
* 查詢數(shù)據(jù)
*/
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 "注冊(cè)成功!";
}
}catch(SQLException ?e){
e.printStackTrace();
return "錯(cuò)誤!";
}
finally{
try {
connection.close();
rs.close();
} catch (SQLException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
return "錯(cuò)誤!";
}
/*
* 查詢數(shù)據(jù)
*/
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();
// 準(zhǔn)備sql語(yǔ)句 ?UPDATE Person SET FirstName = 'Fred' WHERE LastName = 'Wilson'
String sql = "update students set pic=? where id='"+id+"'";
// 獲取PrepareStatement對(duì)象
preparedStatement = connection.prepareStatement(sql,Statement.RETURN_GENERATED_KEYS);
// 填充占位符
preparedStatement.setString(1, picName);
// 執(zhí)行sql
preparedStatement.execute();
return true;
}catch(SQLException ?e){
e.printStackTrace();
return false;
}finally{
JdbcUtils.releaseDB(connection, preparedStatement, null);
}
}
}
3、使用tomcat映射圖片地址
打開(kāi)Tomcat安裝文件夾——>conf——>Catalina——>localhost
創(chuàng)建xml文件 pic.xml (文件名必須與Context path的值一致),docBase與workDir的值為圖片所在文件夾,配置好后可在瀏覽器通過(guò)192.168.0.101:8080/pic/文件名 訪問(wèn)圖片(192.168.0.101:8080為本機(jī)ip與tomcat端口號(hào))
docBase="D:/test"
workDir="D:/test"
debug="0"
reloadable="true"
crossContext="true" />
總結(jié)
以上是生活随笔為你收集整理的app上传头像处理Java_java后台加安卓端实现头像上传功能的全部?jī)?nèi)容,希望文章能夠幫你解決所遇到的問(wèn)題。
- 上一篇: 关于java线程同步的笔记_线程同步(J
- 下一篇: java https通讯_Kuberne