<linearLayout xmlns:androID="http://schemas.androID.com/apk/res/androID" androID:layout_wIDth="fill_parent" androID:layout_height="fill_parent" androID:orIEntation="vertical" androID:background="@color/colorPrimary" > <linearLayout androID:layout_wIDth="wrap_content" androID:layout_marginleft="10dp" androID:layout_marginRight="10dp" androID:layout_height="60dp" androID:layout_margintop="80dp" androID:orIEntation="horizontal"> <TextVIEw androID:layout_wIDth="match_parent" androID:layout_height="50dp" androID:layout_gravity="center_vertical" androID:gravity="center" androID:text="视频名称:" androID:textcolor="#FF8899" androID:textSize="18dp"/> <EditText androID:ID="@+ID/upload_vIDeo_name" androID:layout_wIDth="280dp" androID:layout_height="50dp" androID:layout_gravity="center_vertical" androID:hint="请输入上传视频名称" androID:layout_marginleft="5dp" androID:textSize="18dp" /> </linearLayout> <button androID:ID="@+ID/button1" androID:layout_wIDth="match_parent" androID:layout_height="44dp" androID:layout_marginleft="100dp" androID:layout_marginRight="100dp" androID:layout_margintop="80dp" androID:text="选择视频" androID:textSize="20sp"/> <button androID:ID="@+ID/button" androID:layout_wIDth="match_parent" androID:layout_height="44dp" androID:layout_marginleft="100dp" androID:layout_marginRight="100dp" androID:layout_margintop="40dp" androID:text="点击上传" androID:textSize="20sp"/> <TextVIEw androID:ID="@+ID/post_text" androID:layout_margintop="40dp" androID:layout_wIDth="match_parent" androID:layout_height="wrap_content" androID:gravity="center" androID:text="0" /> <Progressbar androID:ID="@+ID/post_progress" androID:layout_marginleft="20dp" androID:layout_marginRight="20dp" androID:layout_wIDth="match_parent" androID:layout_height="wrap_content" androID:max="100" /></linearLayout>
activate… 在activate 点击上传的时候 发送两个请求 一个是上传视频,一个是上传视频的第一帧 经过压缩 里面还有 几个方法没有用上 复制上无妨package wlt.com.sdk;import androIDx.appcompat.app.AppCompatActivity;import androID.accounts.NetworkErrorException;import androID.content.ContentProvIDer;import androID.content.ContentResolver;import androID.content.Context;import androID.content.Intent;import androID.database.Cursor;import androID.media.MediaMetadataRetrIEver;import androID.net.Uri;import androID.os.Bundle;import androID.os.Handler;import androID.os.Message;import androID.provIDer.MediaStore;import androID.util.Log;import wlt.com.sdk.utils.My_Okhtt3;import wlt.com.sdk.utils.ProgressListener;import androID.vIEw.VIEw;import androID.Widget.button;import androID.Widget.EditText;import androID.Widget.MediaController;import androID.Widget.Progressbar;import androID.Widget.TextVIEw;import androID.Widget.Toast;import org.Json.JsONArray;import org.Json.JsONException;import org.Json.JsONObject;import java.io.file;import java.io.IOException;import java.net.URI;import java.nio.charset.Charset;import okhttp3.Call;import okhttp3.Callback;import okhttp3.FormBody;import okhttp3.OkhttpClIEnt;import okhttp3.Request;import okhttp3.Requestbody;import okhttp3.Response;import wlt.com.sdk.utils.httpUtil;import wlt.com.sdk.utils.kkk;public class MainActivity extends AppCompatActivity { private button button, button1; private String path = "";//文件路径 private Progressbar post_progress; private TextVIEw post_text; EditText vIDeo_name; private String str; @OverrIDe protected voID onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentVIEw(R.layout.activity_main); getSupportActionbar().setTitle("视频上传"); getSupportActionbar().setdisplayHomeAsUpEnabled(true); vIDeo_name = (EditText) findVIEwByID(R.ID.upload_vIDeo_name); init(); onclick2(); onclick(); } //初始化 public voID init() { post_progress = (Progressbar) findVIEwByID(R.ID.post_progress); post_text = (TextVIEw) findVIEwByID(R.ID.post_text); button = (button) this.findVIEwByID(R.ID.button);//开始上传 button1 = (button) this.findVIEwByID(R.ID.button1);//选择视频 }//setText Handler handler=new Handler(new Handler.Callback() { @OverrIDe public boolean handleMessage( Message msg) { if (msg.arg1==1){ vIDeo_name.setText(path); return true; } return false; } });## // 开始上传 public voID onclick() { button.setonClickListener(new VIEw.OnClickListener() { @OverrIDe public voID onClick(VIEw v) { if (path.equals("")) { Toast.makeText(MainActivity.this, "请选择视频后,再点击上传!", Toast.LENGTH_LONG).show(); } else { file file = new file(path); String postUrl = "http://192.168.1.106:8080/img/voIDeoServlet1"; //这个是上传视频 httpUtil.postfile(postUrl, new ProgressListener() { @OverrIDe public voID onProgress(long currentBytes, long contentLength, boolean done) { int progress = (int) (currentBytes * 100 / contentLength); post_progress.setProgress(progress); post_text.setText(progress + "%"); if (progress==100){ Toast.makeText(MainActivity.this,"上传成功" ,Toast.LENGTH_LONG).show(); } } }, new Callback() { @OverrIDe public voID onFailure(Call call, IOException e) { } @OverrIDe public voID onResponse(Call call, Response response) throws IOException { } }, file); try { //这个是上传图片kkk.getNetVIDeoBitmap(path) 通过视频路径 返回bitmap kkk.YaSuoImage(bitmap) 压缩bitmap 返回 file httpUtil.postfileimg("http://192.168.1.106:8080/img/and_imgServlet", new Callback() { @OverrIDe public voID onFailure(Call call, IOException e) { } @OverrIDe public voID onResponse(Call call, Response response) throws IOException { } },kkk.YaSuoImage(kkk.getNetVIDeoBitmap(path))); }catch (Exception e){ e.printstacktrace(); } } } }); } //打开相册 public voID onclick2() { button1.setonClickListener(new VIEw.OnClickListener() { @OverrIDe public voID onClick(VIEw v) { seleteVedio(); } }); } public voID seleteVedio() { Intent i = new Intent(Intent.ACTION_PICK, androID.provIDer.MediaStore.VIDeo.Media.EXTERNAL_CONTENT_URI); startActivityForResult(i, 66); } ## /** * 视频回调 */ @OverrIDe protected voID onActivityResult(int requestCode, int resultCode, Intent data) { super.onActivityResult(requestCode, resultCode, data); System.out.println("---onActivityResult-->>"); if (requestCode == 66 && resultCode == RESulT_OK && null != data) { Uri selectedVIDeo = data.getData(); String[] filePathColumn = {MediaStore.VIDeo.Media.DATA}; Cursor cursor = getContentResolver().query(selectedVIDeo, filePathColumn, null, null, null); cursor.movetoFirst(); int columnIndex = cursor.getColumnIndex(filePathColumn[0]); path = cursor.getString(columnIndex); System.out.println("----------->>>>"+path); Message message=new Message(); message.arg1=1; message.obj=path; handler.sendMessage(message); cursor.close(); } if (resultCode != MainActivity.RESulT_OK) { return; } } }
上传图片的工具类
package wlt.com.sdk.utils;import androID.graphics.Bitmap;import androID.media.MediaMetadataRetrIEver;import androID.os.Environment;import java.io.ByteArrayOutputStream;import java.io.file;import java.io.fileNotFoundException;import java.io.fileOutputStream;import java.io.IOException;import java.text.SimpleDateFormat;import java.util.Date;import java.util.HashMap;import java.util.logging.SimpleFormatter;/** * 获取视频第一帧 */public class kkk { /** * 根据视频地址获取第一帧 * * @param vIDeoUrl * @return */ public static Bitmap getNetVIDeoBitmap(String vIDeoUrl) { Bitmap bitmap = null; MediaMetadataRetrIEver retrIEver = new MediaMetadataRetrIEver(); try { //根据url获取缩略图 retrIEver.setDataSource(vIDeoUrl, new HashMap()); //获得第一帧图片 bitmap = retrIEver.getFrameatTime(); } catch (IllegalArgumentException e) { e.printstacktrace(); } finally { retrIEver.release(); } return bitmap; } /** * 压缩图片 * * @param bitmap * @return */ public static file YaSuoImage(Bitmap bitmap) { ByteArrayOutputStream baos = new ByteArrayOutputStream(); bitmap.compress(Bitmap.CompressFormat.JPEG, 100, baos);//质量压缩方法,这里100表示不压缩,把压缩后的数据存放到baos中 int options = 100; while (baos.toByteArray().length / 1024 > 500) { //循环判断如果压缩后图片是否大于500kb,大于继续压缩 baos.reset();//重置baos即清空baos options -= 10;//每次都减少10 bitmap.compress(Bitmap.CompressFormat.JPEG, options, baos);//这里压缩options%,把压缩后的数据存放到baos中 long length = baos.toByteArray().length; } SimpleDateFormat format = new SimpleDateFormat("yyyyMMddHHmmss"); Date date = new Date(System.currentTimeMillis()); String filename = format.format(date); file file = new file(Environment.getExternalStorageDirectory(), filename + ".png"); try { fileOutputStream fos = new fileOutputStream(file); try { fos.write(baos.toByteArray()); fos.flush(); fos.close(); } catch (IOException e) { e.printstacktrace(); } } catch (fileNotFoundException e) { e.printstacktrace(); } recycleBitmap(bitmap); return file; } public static voID recycleBitmap(Bitmap... bitmaps) { if (bitmaps == null) { return; } for (Bitmap bm : bitmaps) { if (null != bm && !bm.isRecycled()) { bm.recycle(); } } }}
okhttpUtils 工具类
package wlt.com.sdk.utils;import androID.accounts.NetworkErrorException;import androID.util.Log;import java.io.file;import java.util.concurrent.TimeUnit;import okhttp3.Callback;import okhttp3.MediaType;import okhttp3.Multipartbody;import okhttp3.OkhttpClIEnt;import okhttp3.Request;import okhttp3.Requestbody;import okhttp3.Response;public class httpUtil { private static OkhttpClIEnt okhttpClIEnt = new OkhttpClIEnt.Builder().connectTimeout(10000, TimeUnit.MILliSECONDS) .readTimeout(10000, TimeUnit.MILliSECONDS) .writeTimeout(10000, TimeUnit.MILliSECONDS).build(); public static final MediaType JsON = MediaType.parse("application/Json; charset=utf-8"); public static final MediaType MEDIA_TYPE_MARKDOWN = MediaType.parse("text/x-markdown; charset=utf-8"); /** * 上传视频 * @param url * @param Listener * @param callback * @param files */ public static voID postfile(String url, final ProgressListener Listener, okhttp3.Callback callback, file... files) { Multipartbody.Builder builder = new Multipartbody.Builder(); builder.setType(Multipartbody.FORM); Log.i("huang", "files[0].getname()==" + files[0].getname()); //第一个参数要与Servlet中的一致 builder.addFormDataPart("myfile", files[0].getname(), Requestbody.create(MediaType.parse("application/octet-stream"), files[0])); Multipartbody multipartbody = builder.build(); Request request = new Request.Builder().url(url).post(new ProgressRequestbody(multipartbody, Listener)).build(); okhttpClIEnt.newCall(request).enqueue(callback); } /** * 上传图片 * @param url * @param callback * @param files */ private static final MediaType MEDIA_TYPE_PNG = MediaType.parse("image/png"); public static voID postfileimg(String url, okhttp3.Callback callback, file... files) { Requestbody fileBody = Requestbody.create(MEDIA_TYPE_PNG, files[0]); Requestbody requestbody = new Multipartbody.Builder() .setType(Multipartbody.FORM) .addFormDataPart("ss",files[0].getname(),fileBody) // .addFormDataPart("username", username) .build(); Request request = new Request.Builder() .url(url) .post(requestbody) .build(); okhttpClIEnt.newCall(request).enqueue(callback); } /** * 下载图片 * @param url * @param imagePath 图片路径 * @return byte[] */ public static byte[] downloadImage(String url, String imagePath) throws Exception { OkhttpClIEnt okhttpClIEnt = new OkhttpClIEnt(); Request request = new Request.Builder() .url(url+"/show?filename="+imagePath) .build(); Response response = okhttpClIEnt.newCall(request).execute(); byte[] bytes = response.body().bytes(); return bytes; }}
权限 别忘加权限
以上是是androID端 完成 复制代码可用 下面是servletmybatils 使用的是接口方式 接口里面的方法名是Mapper的ID 返回类型也是一样 传的参数一样。。。jdbc.propertIEsdriverClass=oracle.jdbc.driver.OracleDriver
url=jdbc:oracle:thin:@localhost:1521:orcl
user=system
password=wltpas
<?xml version="1.0" enCoding="UTF-8"?><!DOCTYPE configuration PUBliC "-//mybatis.org//DTD Config 3.0//EN" "http://mybatis.org/dtd/mybatis-3-config.dtd"><configuration><!-- <typeAliases> <package name="wlt.com.vo.Student"/> </typeAliases> --> <environments default="development"> <environment ID="development"> <transactionManager type="JDBC"/> <dataSource type="POolED"> <property name="driver" value="oracle.jdbc.driver.OracleDriver"/> <property name="url" value="jdbc:oracle:thin:@localhost:1521:orcl"/> <property name="username" value="system"/> <property name="password" value="wltpass"/> </dataSource> </environment> </environments> <mappers> <mapper resource="wlt/vIDeo/vo/VIDeoVo_Mapper.xml" /> <mapper resource="wlt/vIDeo/vo/VIDeoimg_Mapper.xml" /> </mappers></configuration>
VIDeoVo_Mapper.xml<?xml version="1.0" enCoding="UTF-8"?><!DOCTYPE mapper PUBliC "-//mybatis.org//DTD Mapper 3.0//EN" "http://mybatis.org/dtd/mybatis-3-mapper.dtd"><mapper namespace="wlt.vIDeo.vo.VIDeoimg_Mapper_Imp"> <insert ID="Insertssutdent" parameterType="wlt.vIDeo.vo.VIDeoimg"> insert into vIDeoimg (v_imgurl )values( #{v_imgurl}) </insert> <select ID="SelectAll" resultType="wlt.vIDeo.vo.VIDeoimg"> select * from vIDeoimg </select></mapper>
VIDeoimg_Mapper.xml<?xml version="1.0" enCoding="UTF-8"?><!DOCTYPE mapper PUBliC "-//mybatis.org//DTD Mapper 3.0//EN" "http://mybatis.org/dtd/mybatis-3-mapper.dtd"><mapper namespace="wlt.vIDeo.vo.VIDeoVo_Mapper_Imp"> <insert ID="Insertssutdent" parameterType="wlt.vIDeo.vo.VIDeoVo"> insert into vIDeo (v_url )values( #{v_url}) </insert> <select ID="SelectAll" resultType="wlt.vIDeo.vo.VIDeoVo"> select * from vIDeo </select></mapper>
VIDeoVo_Mapper_Imp package wlt.vIDeo.vo;import java.util.List;public interface VIDeoVo_Mapper_Imp { voID Insertssutdent(VIDeoVo student); List<VIDeoVo> SelectAll();}
VIDeoimg_Mapper_Imppackage wlt.vIDeo.vo;import java.util.List;public interface VIDeoimg_Mapper_Imp { voID Insertssutdent(VIDeoimg student); List<VIDeoimg> SelectAll();}
接着就差vopackage wlt.vIDeo.vo;import java.io.Serializable;public class VIDeoVo implements Serializable{ private String v_url;public String getV_url() { return v_url;}public voID setV_url(String vUrl) { v_url = vUrl;} }package wlt.vIDeo.vo;import java.io.Serializable;public class VIDeoimg implements Serializable{ private String v_imgurl;public String getV_imgurl() { return v_imgurl;}public voID setV_imgurl(String vimgurl) { v_imgurl = vimgurl;} }
MybatisUtilpackage wlt.vIDeo.vo;import java.io.IOException;import java.io.inputStream;import java.io.Reader;import org.apache.ibatis.io.Resources;import org.apache.ibatis.session.sqlSession;import org.apache.ibatis.session.sqlSessionFactory;import org.apache.ibatis.session.sqlSessionFactoryBuilder;public class MybatisUtil { private static sqlSessionFactory ssf; private static sqlSession ss; public static sqlSession getsqlSession(){ try { Reader in = Resources.getResourceAsReader("mybatis-config.xml"); ssf = new sqlSessionFactoryBuilder().build(in); ss = ssf.openSession(); in.close(); } catch (IOException e) { e.printstacktrace(); } return ss; }}
以上 mybatis 完成 servlet 下面图片的servletpackage wlt.img.servlet;import java.io.file;import java.io.IOException;import java.io.PrintWriter;import java.util.List;import javax.servlet.ServletContext;import javax.servlet.servletexception;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.disk.diskfileItemFactory;import org.apache.commons.fileupload.servlet.ServletfileUpload;import org.apache.ibatis.session.sqlSession;import wlt.vIDeo.vo.VIDeoimg;import wlt.vIDeo.vo.VIDeoimg_Mapper_Imp;import wlt.vIDeo.vo.VIDeoVo_Mapper_Imp;@SuppressWarnings("serial")public class and_imgServlet extends httpServlet { @OverrIDe protected voID doPost(httpServletRequest req, httpServletResponse resp) throws servletexception, IOException { req.setCharacterEnCoding("utf-8"); resp.setContentType("text/HTML;charset=utf-8"); resp.setCharacterEnCoding("utf-8"); PrintWriter out = resp.getWriter(); String url=""; sqlSession session=wlt.vIDeo.vo.MybatisUtil.getsqlSession(); VIDeoimg_Mapper_Imp imp= session.getMapper(VIDeoimg_Mapper_Imp.class); // 为解析类提供配置信息 diskfileItemFactory factory = new diskfileItemFactory(); // 创建解析类的实例 ServletfileUpload sfu = new ServletfileUpload(factory); // 开始解析 sfu.setfileSizeMax(1024 * 1024 * 5); // 每个表单域中数据会封装到一个对应的fileItem对象上 try { List<fileItem> items = sfu.parseRequest(req); // 区分表单域 for (int i = 0; i < items.size(); i++) { fileItem item = items.get(i); // isFormFIEld为true,表示这不是文件上传表单域 if (!item.isFormFIEld()) { ServletContext sctx = getServletContext(); // 获得存放文件的物理路径 // upload下的某个文件夹 得到当前在线的用户 找到对应的文件夹 String path = sctx.getRealPath("/upload/images"); System.out.println(path); // 获得文件名 String filename = item.getname(); url="http://192.168.1.106:8080/vIDeo/images/"+filename; VIDeoimg v=new VIDeoimg(); v.setV_imgurl(url); imp.Insertssutdent(v); session.commit(); System.out.println("添加成功"); //E:\cat\apache-tomcat-6.0.29\webapps\img\images System.out.println(filename); // 该方法在某些平台( *** 作系统),会返回路径+文件名 filename = filename .substring(filename.lastIndexOf("/") + 1); file file = new file(path + "\" + filename); System.out.println("--->>" + file); if (!file.exists()) { item.write(file); // 将上传图片的名字记录到数据库中 System.out.println("----------ok-----..."); } } } } catch (Exception e) { e.printstacktrace(); } }}
视频的servltpackage wlt.img.servlet;import java.io.BufferedinputStream;import java.io.ByteArrayOutputStream;import java.io.file;import java.io.fileNotFoundException;import java.io.fileOutputStream;import java.io.IOException;import java.io.inputStream;import java.io.PrintWriter;import java.util.List;import javax.servlet.ServletContext;import javax.servlet.servletexception;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 org.apache.ibatis.session.sqlSession;import wlt.vIDeo.vo.VIDeoVo;import wlt.vIDeo.vo.VIDeoVo_Mapper_Imp;public class voIDeoServlet1 extends httpServlet { public voID doGet(httpServletRequest request, httpServletResponse response) throws servletexception, IOException { this.doPost(request, response); } public voID doPost(httpServletRequest request, httpServletResponse response) throws servletexception, IOException { request.setCharacterEnCoding("utf-8"); response.setContentType("text/HTML;charset=utf-8"); String url=""; sqlSession session=wlt.vIDeo.vo.MybatisUtil.getsqlSession(); VIDeoVo_Mapper_Imp imp= session.getMapper(VIDeoVo_Mapper_Imp.class); PrintWriter out = response.getWriter(); diskfileItemFactory factory=new diskfileItemFactory(); String upload=this.getServletContext().getRealPath("/upload"); System.out.println("--->>:"+upload); factory.setSizeThreshold(1024*1024*5); ServletfileUpload fileUpload=new ServletfileUpload(factory); try { List<fileItem> List=fileUpload.parseRequest(request); System.out.println("==="+List.size()); for (int i = 0; i < List.size(); i++) { fileItem item = List.get(i); ServletContext sctx = getServletContext(); String filename = item.getname(); System.out.println(filename); url="http://192.168.1.106:8080/vIDeo/"+filename; System.out.println("--url->>"+url); VIDeoVo vIDeoVo=new VIDeoVo(); vIDeoVo.setV_url(url); imp.Insertssutdent(vIDeoVo); session.commit(); System.out.println("添加session成功"); System.out.println("--url->>"); // 该方法在某些平台( *** 作系统),会返回路径+文件名 filename = filename .substring(filename.lastIndexOf("/") + 1); file file = new file(upload + "\" + filename); System.out.println("--->>" + file.toString()); if (!file.exists()) { try { item.write(file); System.out.println("----------ss-----..."); //out.print("http://192.168.1.106:8080/img/vIDeo/a.mp4");这个是给AndroIDstudio 返回的 } catch (Exception e) { // Todo auto-generated catch block e.printstacktrace(); } } } } catch (fileUploadException e) { // Todo auto-generated catch block e.printstacktrace(); out.write("no"); } out.flush(); out.close(); } }# web.xml <servlet> <servlet-name>and_imgServlet</servlet-name> <servlet-class>wlt.img.servlet.and_imgServlet</servlet-class> </servlet> <servlet-mapping> <servlet-name>and_imgServlet</servlet-name> <url-pattern>/and_imgServlet</url-pattern> </servlet-mapping> <servlet> <servlet-name>voIDeoServlet1</servlet-name> <servlet-class>wlt.img.servlet.voIDeoServlet1</servlet-class> </servlet> <servlet-mapping> <servlet-name>voIDeoServlet1</servlet-name> <url-pattern>/voIDeoServlet1</url-pattern> </servlet-mapping>## 最后就是tomcat 打开 server.xml添加 可以理解取个别名<Context docBase="E:\cat\apache-tomcat-6.0.29\webapps\img\upload" path="/vIDeo" reloadable="true"/>url="http://192.168.1.106:8080/vIDeo/"+filename; 这个vIDeo==E:\cat\apache-tomcat-6.0.29\webapps\img\upload 这个路径![在这里插入图片描述](https://www.icode9.com/i/ll/?i=202002231338380.png?,type_ZmFuZ3poZW5naGVpdGk,shadow_10,text_aHR0cHM6Ly9ibG9nLmNzZG4ubmV0L3FxXzM4MjE4MzA3,size_16,color_FFFFFF,t_70)## 想一想 ok 能用到 你懂得
点赞收藏分享文章举报qq_38218307发布了3 篇原创文章 · 获赞 0 · 访问量 10私信 关注 总结 以上是内存溢出为你收集整理的android studio上传视频保存数据库 后台servlet mybatis全部内容,希望文章能够帮你解决android studio上传视频保存数据库 后台servlet mybatis所遇到的程序开发问题。
如果觉得内存溢出网站内容还不错,欢迎将内存溢出网站推荐给程序员好友。
欢迎分享,转载请注明来源:内存溢出
评论列表(0条)