文章目录
1.打开IDEA,新建项目作为服务器
- Eclips可以选择“Dynamic web project”
- IDEA可以选择Maven管理的web项目
2.在pom.xml中,导入依赖
- mysql-connector-java
- json
- tomcat
- jsp-api
- servlet
<?xml version="1.0" encoding="UTF-8"?>
<project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
<modelVersion>4.0.0</modelVersion>
<groupId>PhoneServer</groupId>
<artifactId>edu.qau.whr</artifactId>
<version>1.0-SNAPSHOT</version>
<packaging>war</packaging>
<name>edu.qau.whr Maven Webapp</name>
<!-- FIXME change it to the project's website -->
<url>http://www.example.com</url>
<properties>
<project.build.sourceEncoding>UTF-8</project.build.sourceEncoding>
<maven.compiler.source>1.7</maven.compiler.source>
<maven.compiler.target>1.7</maven.compiler.target>
</properties>
<dependencies>
<dependency>
<groupId>junit</groupId>
<artifactId>junit</artifactId>
<version>4.11</version>
<scope>test</scope>
</dependency>
<!-- https://mvnrepository.com/artifact/com.google.code.gson/gson -->
<dependency>
<groupId>com.google.code.gson</groupId>
<artifactId>gson</artifactId>
<version>2.8.5</version>
</dependency>
<!-- https://mvnrepository.com/artifact/ca.uhn.ws/json-rpc-model -->
<dependency>
<groupId>ca.uhn.ws</groupId>
<artifactId>json-rpc-model</artifactId>
<version>1.0</version>
</dependency>
<!-- https://mvnrepository.com/artifact/mysql/mysql-connector-java -->
<dependency>
<groupId>mysql</groupId>
<artifactId>mysql-connector-java</artifactId>
<version>8.0.16</version>
</dependency>
<!-- https://mvnrepository.com/artifact/org.apache.tomcat/tomcat-jsp-api -->
<dependency>
<groupId>org.apache.tomcat</groupId>
<artifactId>tomcat-jsp-api</artifactId>
<version>8.0.36</version>
</dependency>
<!-- https://mvnrepository.com/artifact/org.apache.tomcat/tomcat-servlet-api -->
<dependency>
<groupId>org.apache.tomcat</groupId>
<artifactId>tomcat-servlet-api</artifactId>
<version>8.0.36</version>
</dependency>
<!-- 引入json依赖 -->
<dependency>
<groupId>net.sf.json-lib</groupId>
<artifactId>json-lib</artifactId>
<version>2.4</version>
<classifier>jdk15</classifier>
</dependency>
<dependency>
<groupId>commons-beanutils</groupId>
<artifactId>commons-beanutils</artifactId>
<version>1.7.0</version>
</dependency>
<dependency>
<groupId>commons-collections</groupId>
<artifactId>commons-collections</artifactId>
<version>3.1</version>
</dependency>
<dependency>
<groupId>commons-lang</groupId>
<artifactId>commons-lang</artifactId>
<version>2.5</version>
</dependency>
<dependency>
<groupId>net.sf.ezmorph</groupId>
<artifactId>ezmorph</artifactId>
<version>1.0.3</version>
</dependency>
</dependencies>
<build>
<finalName>edu.qau.whr</finalName>
<pluginManagement><!-- lock down plugins versions to avoid using Maven defaults (may be moved to parent pom) -->
<plugins>
<plugin>
<artifactId>maven-clean-plugin</artifactId>
<version>3.1.0</version>
</plugin>
<!-- see http://maven.apache.org/ref/current/maven-core/default-bindings.html#Plugin_bindings_for_war_packaging -->
<plugin>
<artifactId>maven-resources-plugin</artifactId>
<version>3.0.2</version>
</plugin>
<plugin>
<artifactId>maven-compiler-plugin</artifactId>
<version>3.8.0</version>
</plugin>
<plugin>
<artifactId>maven-surefire-plugin</artifactId>
<version>2.22.1</version>
</plugin>
<plugin>
<artifactId>maven-war-plugin</artifactId>
<version>3.2.2</version>
</plugin>
<plugin>
<artifactId>maven-install-plugin</artifactId>
<version>2.5.2</version>
</plugin>
<plugin>
<artifactId>maven-deploy-plugin</artifactId>
<version>2.8.2</version>
</plugin>
</plugins>
</pluginManagement>
</build>
</project>
3.新建Image的Bean类
包名:edu.qau.server.bean
类名:Image
具有 path,name,flag成员属性
package edu.qau.server.bean;
public class Image {
private String path;
private String name;
private int flag;
public String getPath() {
return path;
}
public void setPath(String path) {
this.path = path;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public int getFlag() {
return flag;
}
public void setFlag(int flag) {
this.flag = flag;
}
}
4.新建Talk的Bean类
包名:edu.qau.server.bean
类名:Talk
具有 id,talk,list,goods成员属性。
package edu.qau.server.bean;
import java.util.ArrayList;
public class Talk {
private long id;
private String talk;
private ArrayList<Image> list;
private int goods;
public long getId() {
return id;
}
public void setId(long id) {
this.id = id;
}
public String getTalk() {
return talk;
}
public void setTalk(String talk) {
this.talk = talk;
}
public ArrayList<Image> getList() {
return list;
}
public void setList(ArrayList<Image> list) {
this.list = list;
}
public int getGoods() {
return goods;
}
public void setGoods(int goods) {
this.goods = goods;
}
}
5.处理Request
包名:edu.qau.server.action
类名:AddTalk
package edu.qau.server.action;
import com.google.gson.Gson;
import edu.qau.server.bean.Image;
import edu.qau.server.bean.Talk;
import net.sf.json.JSONObject;
import javax.servlet.ServletException;
import javax.servlet.annotation.MultipartConfig;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.Part;
import java.io.*;
import java.util.ArrayList;
@MultipartConfig
@WebServlet("/file")
public class AddTalk extends HttpServlet {
@Override
protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
JSONObject obj=new JSONObject();
try {
String path=req.getServletContext().getRealPath("upload");
Part json=req.getPart("json");
Gson gson=new Gson();
Talk talk=gson.fromJson(new InputStreamReader(json.getInputStream(),"UTF-8"),Talk.class);
System.out.println(path);
System.out.println(talk.getTalk());
ArrayList<Image> list=talk.getList();
for (int i = 0; i < list.size(); i++) {
Image image=list.get(i);
String name=System.currentTimeMillis()+image.getName();
image.setName(name);
File file=new File(path,name);
BufferedOutputStream bos=null;
BufferedInputStream bis=null;
try {
bos=new BufferedOutputStream(new FileOutputStream(file));
bis=new BufferedInputStream(req.getPart("file"+i).getInputStream());
byte[] bytes=new byte[8192];
int len;
while ((len=bis.read(bytes))!=-1){
bos.write(bytes,0,len);
}
} catch (Exception e) {
throw e;
}finally {
if (bos != null) {
bos.close();
}
if (bis != null) {
bis.close();
}
}
}
obj.accumulate("result","success");
} catch (Exception e) {
e.printStackTrace();
obj.accumulate("result","failure");
}
PrintWriter out=resp.getWriter();
out.print(obj.toString());
out.flush();
out.close();
}
}
6.在主服务器下新建upload文件夹
7.打开Android Studio,新建NetWorkUtils类
包名:edu.qau.utils
类名:NetWorkUtils
package edu.qau.utils;
import android.content.Context;
import android.net.ConnectivityManager;
import android.net.NetworkInfo;
import android.telephony.TelephonyManager;
/**
* 判断手机信号:没有网络-0 WIFI网络-1 4G网络-4 3G网络-3 2G网络-2
*/
public class NetWorkUtils {
public static int getAPNType(Context context) {
//网络类型返回值
int netType = 0;
//获取手机所有连接管理对象
ConnectivityManager manager = (ConnectivityManager) context.getSystemService(Context.CONNECTIVITY_SERVICE);
//获取NetworkInfo对象
NetworkInfo networkInfo = manager.getActiveNetworkInfo();
//NetworkInfo为空,则代表无网络
if (networkInfo == null) {
return netType;
}
//如果不为空,获取NetworkIfo内容
int notNullType = networkInfo.getSubtype();
//WIFI
if (notNullType == ConnectivityManager.TYPE_WIFI) {
netType = 1;
} else if (notNullType == ConnectivityManager.TYPE_MOBILE) {
int nSubType = networkInfo.getSubtype();
TelephonyManager telephonyManager = (TelephonyManager) context.getSystemService(Context.TELEPHONY_SERVICE);
//3G联通-UMTS-HSDPA,电信3G-EVDO
if (nSubType == telephonyManager.NETWORK_TYPE_LTE && !telephonyManager.isNetworkRoaming()) {
netType = 4;
} else if (nSubType == TelephonyManager.NETWORK_TYPE_UMTS
|| nSubType == TelephonyManager.NETWORK_TYPE_HSDPA
|| nSubType == TelephonyManager.NETWORK_TYPE_EVDO_0
&& telephonyManager.isNetworkRoaming()) {
netType = 2;
} else {
netType = 1;
}
}
return netType;
}
}
8.在ActicityMain中,加载布局
private int count = 0;//图片数量
private LinearLayout group;//图片显示布局
private ArrayList<Image> list;//图片存放集合
private EditText talkEditText;
onCreate方法中加载布局:
talkEditText = findViewById(R.id.talk);
9.新建Talk的Bean类
包名:edu.qau.bean
类名:Talk
package edu.qau.bean;
import java.util.ArrayList;
public class Talk {
private long id;
private String talk;
private ArrayList<Image> list;
private int goods;
public long getId() {
return id;
}
public void setId(long id) {
this.id = id;
}
public String getTalk() {
return talk;
}
public void setTalk(String talk) {
this.talk = talk;
}
public ArrayList<Image> getList() {
return list;
}
public void setList(ArrayList<Image> list) {
this.list = list;
}
public int getGoods() {
return goods;
}
public void setGoods(int goods) {
this.goods = goods;
}
}
10.在ActicityMain中,指定上传图片类型
private MediaType JPEG = MediaType.parse("image/jpeg");
11.获取图片角度,处理图片角度
在ImageUtils下新建2个函数:
- readPictureDegree()
- rotatingImageView()
**
* 获取图片旋转角度
*
* @param path 获取图片真实路径
* @return 返回图片角度
*/
public static int readPictureDegree(String path) {
int degree = 0;
try {
ExifInterface exifInterface = new ExifInterface(path);
int orientation = exifInterface.getAttributeInt(
ExifInterface.TAG_ORIENTATION,
ExifInterface.ORIENTATION_NORMAL);
switch (orientation) {
case ExifInterface.ORIENTATION_ROTATE_90:
degree = 90;
case ExifInterface.ORIENTATION_ROTATE_180:
degree = 180;
case ExifInterface.ORIENTATION_ROTATE_270:
degree = 270;
default:
break;
}
} catch (IOException e) {
e.printStackTrace();
}
return degree;
}
/**
* 执行旋转图片
*
* @param bitmap 图片本体
* @param degree readPictureDegree()传入的角度信息
* @return
*/
public static Bitmap rotatingImageView(Bitmap bitmap, int degree) {
if (degree != 0) {
Matrix matrix = new Matrix();
matrix.postRotate(degree);
Bitmap newBitmap = Bitmap.createBitmap(bitmap
, 0, 0,
bitmap.getWidth(), bitmap.getHeight(),
matrix, true);
bitmap.recycle();
return newBitmap;
}
return bitmap;
}
12.压缩图片
在ImageUtils下新建函数:
- compressBitmap()
- compressImage()
/**
* 执行压缩图片
*
* @param bitmap 图片本体
* @param path 图片路径
* @param byteArrayOutputStream
* @param size 最大图片大小,大小单位:MB
*/
public static void compressBitmap(Bitmap bitmap, String path, ByteArrayOutputStream byteArrayOutputStream, int size) {
Bitmap.CompressFormat format = null;
if (path.endsWith(".png") || path.endsWith("PNG")) {
format = Bitmap.CompressFormat.PNG;
} else {
format = Bitmap.CompressFormat.JPEG;
}
//压缩比例
int options = 100;
bitmap.compress(format, options, byteArrayOutputStream);
while (byteArrayOutputStream.size() / 1024 > size) {
if (options == 0) {
break;
}
byteArrayOutputStream.reset();
options -= 10;
bitmap.compress(format, options, byteArrayOutputStream);
}
}
/**
* @param picPath
* @param size
* @return
*/
public static ByteArrayOutputStream compressImage(String picPath, int size) {
Bitmap bitmap = BitmapFactory.decodeFile(picPath);
Bitmap resizeBitmap = rotatingImageView(bitmap, readPictureDegree(picPath));
ByteArrayOutputStream byteArrayOutputStream = new ByteArrayOutputStream();
compressBitmap(resizeBitmap, picPath, byteArrayOutputStream, size);
bitmap.recycle();
bitmap = null;
resizeBitmap.recycle();
resizeBitmap = null;
return byteArrayOutputStream;
}
}
13.新建OkHttp工具类
package edu.qau.utils;
import okhttp3.OkHttpClient;
public class OkHttpUtils {
public static final OkHttpClient CLIENT=new OkHttpClient();
}
14.ImageUtils源码
package edu.qau.utils;
import android.content.Context;
import android.database.Cursor;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.graphics.Matrix;
import android.media.ExifInterface;
import android.net.Uri;
import android.provider.MediaStore;
import java.io.ByteArrayOutputStream;
import java.io.IOException;
public class ImageUtils {
/**
* 函数名称:getPath()
* 函数功能:获取图片路径
*
* @param context
* @param uri
* @return 图片路径
*/
public static String getPath(Context context, Uri uri) {
String path = null;
Cursor cursor = context.getContentResolver()
.query(uri, new String[]{MediaStore.Images.Media.DATA},
null, null, null);
if (cursor != null) {
cursor.moveToFirst();
int columnIndex = cursor
.getColumnIndex(MediaStore.Images.Media.DATA);
path = cursor.getString(columnIndex);
cursor.close();
}
return path;
}
/**
* 获取图片旋转角度
*
* @param path 获取图片真实路径
* @return 返回图片角度
*/
public static int readPictureDegree(String path) {
int degree = 0;
try {
ExifInterface exifInterface = new ExifInterface(path);
int orientation = exifInterface.getAttributeInt(
ExifInterface.TAG_ORIENTATION,
ExifInterface.ORIENTATION_NORMAL);
switch (orientation) {
case ExifInterface.ORIENTATION_ROTATE_90:
degree = 90;
case ExifInterface.ORIENTATION_ROTATE_180:
degree = 180;
case ExifInterface.ORIENTATION_ROTATE_270:
degree = 270;
default:
break;
}
} catch (IOException e) {
e.printStackTrace();
}
return degree;
}
/**
* 执行旋转图片
*
* @param bitmap 图片本体
* @param degree readPictureDegree()传入的角度信息
* @return
*/
public static Bitmap rotatingImageView(Bitmap bitmap, int degree) {
if (degree != 0) {
Matrix matrix = new Matrix();
matrix.postRotate(degree);
Bitmap newBitmap = Bitmap.createBitmap(bitmap
, 0, 0,
bitmap.getWidth(), bitmap.getHeight(),
matrix, true);
bitmap.recycle();
return newBitmap;
}
return bitmap;
}
/**
* 执行压缩图片
*
* @param bitmap 图片本体
* @param path 图片路径
* @param byteArrayOutputStream
* @param size 最大图片大小,大小单位:MB
*/
public static void compressBitmap(Bitmap bitmap, String path, ByteArrayOutputStream byteArrayOutputStream, int size) {
Bitmap.CompressFormat format = null;
if (path.endsWith(".png") || path.endsWith("PNG")) {
format = Bitmap.CompressFormat.PNG;
} else {
format = Bitmap.CompressFormat.JPEG;
}
//压缩比例
int options = 100;
bitmap.compress(format, options, byteArrayOutputStream);
while (byteArrayOutputStream.size() / 1024 > size) {
if (options == 0) {
break;
}
byteArrayOutputStream.reset();
options -= 10;
bitmap.compress(format, options, byteArrayOutputStream);
}
}
/**
* @param picPath
* @param size
* @return
*/
public static ByteArrayOutputStream compressImage(String picPath, int size) {
Bitmap bitmap = BitmapFactory.decodeFile(picPath);
Bitmap resizeBitmap = rotatingImageView(bitmap, readPictureDegree(picPath));
ByteArrayOutputStream byteArrayOutputStream = new ByteArrayOutputStream();
compressBitmap(resizeBitmap, picPath, byteArrayOutputStream, size);
bitmap.recycle();
bitmap = null;
resizeBitmap.recycle();
resizeBitmap = null;
return byteArrayOutputStream;
}
}