客户端代码
布局
<?xml version="1.0" encoding="utf-8"?>
<androidx.constraintlayout.widget.ConstraintLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:app="http://schemas.android.com/apk/res-auto"
xmlns:tools="http://schemas.android.com/tools"
android:id="@+id/layout"
android:layout_width="match_parent"
android:layout_height="match_parent"
tools:context=".MainActivity3">
<androidx.constraintlayout.widget.Guideline
android:id="@+id/guideline9"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:orientation="horizontal"
app:layout_constraintGuide_percent="0.17" />
<EditText
android:id="@+id/textView"
android:layout_width="0dp"
android:layout_height="0dp"
android:hint="广告"
app:layout_constraintBottom_toTopOf="@+id/guideline9"
app:layout_constraintEnd_toEndOf="parent"
app:layout_constraintStart_toStartOf="parent"
app:layout_constraintTop_toTopOf="parent"
app:layout_constraintVertical_bias="0.142" />
<ImageButton
android:id="@+id/btn_take"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_marginStart="36dp"
android:layout_marginLeft="36dp"
android:layout_marginTop="36dp"
android:background="@drawable/ic_cam"
app:layout_constraintStart_toStartOf="parent"
app:layout_constraintTop_toTopOf="@+id/guideline9" />
<ImageButton
android:id="@+id/btn_select"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_marginTop="36dp"
android:layout_marginEnd="44dp"
android:layout_marginRight="44dp"
android:background="@drawable/ic_photo"
app:layout_constraintEnd_toEndOf="parent"
app:layout_constraintTop_toTopOf="@+id/guideline9" />
<androidx.constraintlayout.widget.Guideline
android:id="@+id/guideline10"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:orientation="horizontal"
app:layout_constraintGuide_percent="0.38" />
<ImageView
android:id="@+id/imageView"
android:layout_width="fill_parent"
android:layout_height="200dp"
android:layout_marginLeft="30dp"
android:layout_marginTop="20dp"
android:layout_marginRight="30dp"
android:layout_marginBottom="10dp"
app:layout_constraintEnd_toEndOf="parent"
app:layout_constraintStart_toStartOf="parent"
app:layout_constraintTop_toTopOf="@+id/guideline10" />
<Button
android:id="@+id/button6"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_marginTop="24dp"
android:layout_marginEnd="148dp"
android:layout_marginRight="148dp"
android:gravity="center"
android:text="发布"
app:layout_constraintEnd_toEndOf="parent"
app:layout_constraintTop_toBottomOf="@+id/imageView"
tools:ignore="MissingConstraints" />
</androidx.constraintlayout.widget.ConstraintLayout>
activity
//调用照相的
btn_take.setOnClickListener(new View.OnClickListener()
{
@Override
public void onClick(View v)
{
Intent intent = new Intent(MediaStore.ACTION_IMAGE_CAPTURE);//调用android自带的照相机
Uri photoUri = MediaStore.Images.Media.EXTERNAL_CONTENT_URI;
startActivityForResult(intent, 1);
}
});
//打开图库选择图片
btn_select.setOnClickListener(new View.OnClickListener()
{
@Override
public void onClick(View v)
{
Intent i = new Intent(Intent.ACTION_PICK,
MediaStore.Images.Media.EXTERNAL_CONTENT_URI);//调用android的图库
startActivityForResult(i, 2);
}
});
btn_register.setOnClickListener(new View.OnClickListener()
{
@Override
public void onClick(View v)
{
advertise= (String) text_ad.getText().toString();
new Thread(new Runnable()
{
@Override
public void run()
{
MediaType mediaType = MediaType.parse("image/*");
RequestBody filebody = MultipartBody.create(mediaType, file);
MultipartBody.Builder multiBuilder = new MultipartBody.Builder();
//这里是 封装上传图片参数
multiBuilder.addFormDataPart("image", file.getName(), filebody);
//参数以添加header方式将参数封装,否则上传参数为空
// 设置请求体
multiBuilder.setType(MultipartBody.FORM);
HashMap<String, String> params = new HashMap<>();
params.put("advertise", advertise);
params.put("account", account1);
//参数以添加header方式将参数封装,否则上传参数为空
if (params != null && !params.isEmpty())
{
for (String key : params.keySet())
{
multiBuilder.addPart(
Headers.of("Content-Disposition",
"form-data; name=\"" + key + "\""),
RequestBody.create(null, params.get(key)));
}
}
RequestBody multiBody = multiBuilder
.build();
OkHttpClient okHttpClient = new OkHttpClient();
Request request = new Request.Builder().url("http://10.0.2" +
".2:8080/advertise").post(multiBody).build();
try
{
okHttpClient.newCall(request).execute();
} catch (IOException e)
{
e.printStackTrace();
}
}
}).start();
}
});
}
//照相与调用图库两种方式的获取图片bitmap方式。
@Override
protected void onActivityResult(int requestCode, int resultCode, final Intent data)
{
super.onActivityResult(requestCode, resultCode, data);
if (resultCode == Activity.RESULT_OK)
{
if (requestCode == 1)
{ // 拍照
Bundle extras = data.getExtras();
Bitmap photoBit = (Bitmap) extras.get("data");
Bitmap option = BitmapOption.bitmapOption(photoBit, 5);
view_ad.setImageBitmap(option);
String name = DateFormat.format("yyyyMMdd_hhmmss", Calendar.getInstance(Locale.CHINA)) + ".jpg";
saveBitmap2file(option, name);
file = new File("/sdcard/" +name);
Log.e("TAG", "file333333333333333 " + file.getName());
} else if (requestCode == 2)
{ // 相册
try
{
Uri uri = data.getData();
String[] pojo = {MediaStore.Images.Media.DATA};
Cursor cursor = managedQuery(uri, pojo, null, null, null);
if (cursor != null)
{
ContentResolver cr = this.getContentResolver();
int colunm_index =
cursor.getColumnIndexOrThrow(MediaStore.Images.Media.DATA);
cursor.moveToFirst();
String path = cursor.getString(colunm_index);
Log.e("TAG", "file333333333333333 " + path);
file = new File(path);
Bitmap bitmap = BitmapFactory.decodeStream(cr.openInputStream(uri));
Bitmap option = BitmapOption.bitmapOption(bitmap, 5);
view_ad.setImageBitmap(option);//设置为头像的背景
Log.e("TAG", "fiels11111 " + file.getName());
}
} catch (Exception e)
{
}
}
}
}
static boolean saveBitmap2file(Bitmap bmp, String filename)
{
Bitmap.CompressFormat format = Bitmap.CompressFormat.JPEG;
int quality = 100;
OutputStream stream = null;
try
{
stream = new FileOutputStream("/sdcard/" + filename);
} catch (FileNotFoundException e)
{
// TODO Auto-generated catch block
e.printStackTrace();
}
return bmp.compress(format, quality, stream);
}
}
var foo = 'bar';
后端代码
依然java springboot,数据库mysql 图片信息存储在数据库里面
package com.example.ditanbao.Controller;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.dao.DataAccessException;
import org.springframework.jdbc.core.JdbcTemplate;
import org.springframework.jdbc.core.PreparedStatementCallback;
import org.springframework.jdbc.core.PreparedStatementCreator;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.multipart.MultipartFile;
import java.io.*;
import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.SQLException;
@RestController
public class Adcontroller implements Serializable
{
private static final long serialVersionUID = 1L;
@Autowired
private JdbcTemplate jdbcTemplate;
public Adcontroller()
{
super();
}
@ResponseBody
@PostMapping("advertise")
public int Advertise(@RequestParam("image") MultipartFile image,@RequestParam("account") String account,@RequestParam("advertise") String advertise) throws IOException, SQLException
{
File file = MultipartFileToFile(image);
InputStream in;
in = new BufferedInputStream(new FileInputStream(file));
String sql="update table_user_password set advertise="+"'"+advertise+"'"+" where username = "+account;
jdbcTemplate.update(sql);
//数据库插入图片文件
sql="update table_user_password set picture = ? where username ="+account;
String finalSql = sql;
jdbcTemplate.update(new PreparedStatementCreator()
{
@Override
public PreparedStatement createPreparedStatement(Connection connection) throws SQLException
{
PreparedStatement preparedStatement = connection.prepareStatement(finalSql);
preparedStatement.setBinaryStream(1,in);
return preparedStatement;
}
});
return 1;
}
//MultipartFile 转换为file文件
public static File MultipartFileToFile(MultipartFile multiFile) {
// 获取文件名
String fileName = multiFile.getOriginalFilename();
// 获取文件后缀
String prefix = fileName.substring(fileName.lastIndexOf("."));
// 若需要防止生成的临时文件重复,可以在文件名后添加随机码
try {
File file = File.createTempFile(fileName, prefix);
multiFile.transferTo(file);
return file;
} catch (Exception e) {
e.printStackTrace();
}
return null;
}
}