一:服务器端:
1:struts-config.xml
- <?xml version="1.0" encoding="UTF-8" ?>
- <!DOCTYPE struts-config (View Source for full doctype...)>
- - <struts-config>
- - <form-beans>
- <form-bean name="videoForm" type="cn.itcast.formbean.VideoForm" />
- </form-beans>
- - <action-mappings>
- - <action path="/video/list" name="videoForm" scope="request" type="cn.itcast.action.VideoListAction">
- <forward name="video" path="/WEB-INF/page/videos.jsp" />
- <forward name="jsonvideo" path="/WEB-INF/page/jsonvideos.jsp" />
- </action>
- - <action path="/video/manage" name="videoForm" scope="request" type="cn.itcast.action.VideoManageAction" parameter="method">
- <forward name="result" path="/WEB-INF/page/result.jsp" />
- </action>
- </action-mappings>
- </struts-config>
2:VideoForm
- package cn.itcast.formbean;
-
- import org.apache.struts.action.ActionForm;
- import org.apache.struts.upload.FormFile;
-
- public class VideoForm extends ActionForm {
- private String format;
- private String title;
- private Integer timelength;
- private FormFile video;
-
- public FormFile getVideo() {
- return video;
- }
-
- public void setVideo(FormFile video) {
- this.video = video;
- }
-
- public String getTitle() {
- return title;
- }
-
- public void setTitle(String title) {
- this.title = title;
- }
-
- public Integer getTimelength() {
- return timelength;
- }
-
- public void setTimelength(Integer timelength) {
- this.timelength = timelength;
- }
-
- public String getFormat() {
- return format;
- }
-
- public void setFormat(String format) {
- this.format = format;
- }
-
- }
3:VideoManageAction.java
- package cn.itcast.action;
-
- import java.io.File;
- import java.io.FileOutputStream;
- import java.io.InputStream;
-
- import javax.servlet.http.HttpServletRequest;
- import javax.servlet.http.HttpServletResponse;
-
- import org.apache.struts.action.ActionForm;
- import org.apache.struts.action.ActionForward;
- import org.apache.struts.action.ActionMapping;
- import org.apache.struts.actions.DispatchAction;
-
- import cn.itcast.formbean.VideoForm;
- import cn.itcast.utils.StreamTool;
-
- public class VideoManageAction extends DispatchAction {
-
- public ActionForward save(ActionMapping mapping, ActionForm form,
- HttpServletRequest request, HttpServletResponse response)
- throws Exception {
- VideoForm formbean = (VideoForm)form;
- if("GET".equals(request.getMethod())){
- byte[] data = request.getParameter("title").getBytes("ISO-8859-1");
- String title = new String(data, "UTF-8");
- System.out.println("title:"+ title);
- System.out.println("timelength:"+ formbean.getTimelength());
- }else{
- System.out.println("title:"+ formbean.getTitle());
- System.out.println("timelength:"+ formbean.getTimelength());
- }
-
- if(formbean.getVideo()!=null && formbean.getVideo().getFileSize()>0){
- String realpath = request.getSession().getServletContext().getRealPath("/video");
- System.out.println(realpath);
- File dir = new File(realpath);
- if(!dir.exists()) dir.mkdirs();
- File videoFile = new File(dir, formbean.getVideo().getFileName());
- FileOutputStream outStream = new FileOutputStream(videoFile);
- outStream.write(formbean.getVideo().getFileData());
- outStream.close();
- }
- return mapping.findForward("result");
- }
-
- public ActionForward getXML(ActionMapping mapping, ActionForm form,
- HttpServletRequest request, HttpServletResponse response)
- throws Exception {
- InputStream inStream = request.getInputStream();
- byte[] data = StreamTool.readInputStream(inStream);
- String xml = new String(data, "UTF-8");
- System.out.println(xml);
- return mapping.findForward("result");
- }
- }
4:result.jsp
- <%@ page language="java" contentType="text/html; charset=UTF-8"
- pageEncoding="UTF-8"%>
- <!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">
- <html>
- <head>
- <meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
- <title>Insert title here</title>
- </head>
- <body>
- 保存完成
- </body>
- </html>
二:客户端
1:FormFile.java
- package cn.itcast.utils;
-
- import java.io.File;
- import java.io.FileInputStream;
- import java.io.FileNotFoundException;
- import java.io.InputStream;
-
-
-
-
- public class FormFile {
-
- private byte[] data;
- private InputStream inStream;
- private File file;
-
- private String filname;
-
- private String parameterName;
-
- private String contentType = "application/octet-stream";
-
- public FormFile(String filname, byte[] data, String parameterName, String contentType) {
- this.data = data;
- this.filname = filname;
- this.parameterName = parameterName;
- if(contentType!=null) this.contentType = contentType;
- }
-
- public FormFile(String filname, File file, String parameterName, String contentType) {
- this.filname = filname;
- this.parameterName = parameterName;
- this.file = file;
- try {
- this.inStream = new FileInputStream(file);
- } catch (FileNotFoundException e) {
- e.printStackTrace();
- }
- if(contentType!=null) this.contentType = contentType;
- }
-
- public File getFile() {
- return file;
- }
-
- public InputStream getInStream() {
- return inStream;
- }
-
- public byte[] getData() {
- return data;
- }
-
- public String getFilname() {
- return filname;
- }
-
- public void setFilname(String filname) {
- this.filname = filname;
- }
-
- public String getParameterName() {
- return parameterName;
- }
-
- public void setParameterName(String parameterName) {
- this.parameterName = parameterName;
- }
-
- public String getContentType() {
- return contentType;
- }
-
- public void setContentType(String contentType) {
- this.contentType = contentType;
- }
-
- }
2:StreamTool
- package cn.itcast.utils;
-
- import java.io.ByteArrayOutputStream;
- import java.io.InputStream;
-
- public class StreamTool {
-
-
-
-
-
-
-
- public static byte[] readInputStream(InputStream inStream) throws Exception{
- ByteArrayOutputStream outSteam = new ByteArrayOutputStream();
- byte[] buffer = new byte[1024];
- int len = 0;
- while( (len = inStream.read(buffer)) !=-1 ){
- outSteam.write(buffer, 0, len);
- }
- outSteam.close();
- inStream.close();
- return outSteam.toByteArray();
- }
- }
3:SocketHttpRequester.java
- package cn.itcast.utils;
-
- import java.io.BufferedReader;
- import java.io.ByteArrayOutputStream;
- import java.io.DataOutputStream;
- import java.io.InputStream;
- import java.io.InputStreamReader;
- import java.io.OutputStream;
- import java.net.HttpURLConnection;
- import java.net.InetAddress;
- import java.net.Socket;
- import java.net.URL;
- import java.net.URLEncoder;
- import java.util.ArrayList;
- import java.util.List;
- import java.util.Map;
-
- import org.apache.http.HttpResponse;
- import org.apache.http.NameValuePair;
- import org.apache.http.client.HttpClient;
- import org.apache.http.client.entity.UrlEncodedFormEntity;
- import org.apache.http.client.methods.HttpPost;
- import org.apache.http.impl.client.DefaultHttpClient;
- import org.apache.http.message.BasicNameValuePair;
-
- public class SocketHttpRequester {
-
-
-
-
-
-
-
-
- public static byte[] postXml(String path, String xml, String encoding) throws Exception{
- byte[] data = xml.getBytes(encoding);
- URL url = new URL(path);
- HttpURLConnection conn = (HttpURLConnection)url.openConnection();
- conn.setRequestMethod("POST");
- conn.setDoOutput(true);
- conn.setRequestProperty("Content-Type", "text/xml; charset="+ encoding);
- conn.setRequestProperty("Content-Length", String.valueOf(data.length));
- conn.setConnectTimeout(5 * 1000);
- OutputStream outStream = conn.getOutputStream();
- outStream.write(data);
- outStream.flush();
- outStream.close();
- if(conn.getResponseCode()==200){
- return readStream(conn.getInputStream());
- }
- return null;
- }
-
-
-
-
-
-
-
-
-
-
-
-
-
- public static boolean post(String path, Map<String, String> params, FormFile[] files) throws Exception{
- final String BOUNDARY = "---------------------------7da2137580612";
- final String endline = "--" + BOUNDARY + "--\r\n";
-
- int fileDataLength = 0;
- for(FormFile uploadFile : files){
- StringBuilder fileExplain = new StringBuilder();
- fileExplain.append("--");
- fileExplain.append(BOUNDARY);
- fileExplain.append("\r\n");
- fileExplain.append("Content-Disposition: form-data;name=\""+ uploadFile.getParameterName()+"\";filename=\""+ uploadFile.getFilname() + "\"\r\n");
- fileExplain.append("Content-Type: "+ uploadFile.getContentType()+"\r\n\r\n");
- fileExplain.append("\r\n");
- fileDataLength += fileExplain.length();
- if(uploadFile.getInStream()!=null){
- fileDataLength += uploadFile.getFile().length();
- }else{
- fileDataLength += uploadFile.getData().length;
- }
- }
- StringBuilder textEntity = new StringBuilder();
- for (Map.Entry<String, String> entry : params.entrySet()) {
- textEntity.append("--");
- textEntity.append(BOUNDARY);
- textEntity.append("\r\n");
- textEntity.append("Content-Disposition: form-data; name=\""+ entry.getKey() + "\"\r\n\r\n");
- textEntity.append(entry.getValue());
- textEntity.append("\r\n");
- }
-
- int dataLength = textEntity.toString().getBytes().length + fileDataLength + endline.getBytes().length;
-
- URL url = new URL(path);
- int port = url.getPort()==-1 ? 80 : url.getPort();
- Socket socket = new Socket(InetAddress.getByName(url.getHost()), port);
- OutputStream outStream = socket.getOutputStream();
-
- String requestmethod = "POST "+ url.getPath()+" HTTP/1.1\r\n";
- outStream.write(requestmethod.getBytes());
- String accept = "Accept: image/gif, image/jpeg, image/pjpeg, image/pjpeg, application/x-shockwave-flash, application/xaml+xml, application/vnd.ms-xpsdocument, application/x-ms-xbap, application/x-ms-application, application/vnd.ms-excel, application/vnd.ms-powerpoint, application/msword, */*\r\n";
- outStream.write(accept.getBytes());
- String language = "Accept-Language: zh-CN\r\n";
- outStream.write(language.getBytes());
- String contenttype = "Content-Type: multipart/form-data; boundary="+ BOUNDARY+ "\r\n";
- outStream.write(contenttype.getBytes());
- String contentlength = "Content-Length: "+ dataLength + "\r\n";
- outStream.write(contentlength.getBytes());
- String alive = "Connection: Keep-Alive\r\n";
- outStream.write(alive.getBytes());
- String host = "Host: "+ url.getHost() +":"+ port +"\r\n";
- outStream.write(host.getBytes());
-
- outStream.write("\r\n".getBytes());
-
- outStream.write(textEntity.toString().getBytes());
-
- for(FormFile uploadFile : files){
- StringBuilder fileEntity = new StringBuilder();
- fileEntity.append("--");
- fileEntity.append(BOUNDARY);
- fileEntity.append("\r\n");
- fileEntity.append("Content-Disposition: form-data;name=\""+ uploadFile.getParameterName()+"\";filename=\""+ uploadFile.getFilname() + "\"\r\n");
- fileEntity.append("Content-Type: "+ uploadFile.getContentType()+"\r\n\r\n");
- outStream.write(fileEntity.toString().getBytes());
- if(uploadFile.getInStream()!=null){
- byte[] buffer = new byte[1024];
- int len = 0;
- while((len = uploadFile.getInStream().read(buffer, 0, 1024))!=-1){
- outStream.write(buffer, 0, len);
- }
- uploadFile.getInStream().close();
- }else{
- outStream.write(uploadFile.getData(), 0, uploadFile.getData().length);
- }
- outStream.write("\r\n".getBytes());
- }
-
- outStream.write(endline.getBytes());
-
- BufferedReader reader = new BufferedReader(new InputStreamReader(socket.getInputStream()));
- if(reader.readLine().indexOf("200")==-1){
- return false;
- }
- outStream.flush();
- outStream.close();
- reader.close();
- socket.close();
- return true;
- }
-
- /**
- * 提交数据到服务器
- * @param path 上传路径(注:避免使用localhost或127.0.0.1这样的路径测试,因为它会指向手机模拟器,你可以使用http:
- * @param params 请求参数 key为参数名,value为参数值
- * @param file 上传文件
- */
- public static boolean post(String path, Map<String, String> params, FormFile file) throws Exception{
- return post(path, params, new FormFile[]{file});
- }
-
-
-
-
-
-
- public static byte[] postFromHttpClient(String path, Map<String, String> params, String encode) throws Exception{
- List<NameValuePair> formparams = new ArrayList<NameValuePair>();
- for(Map.Entry<String, String> entry : params.entrySet()){
- formparams.add(new BasicNameValuePair(entry.getKey(), entry.getValue()));
- }
- UrlEncodedFormEntity entity = new UrlEncodedFormEntity(formparams, encode);
- HttpPost httppost = new HttpPost(path);
- httppost.setEntity(entity);
- HttpClient httpclient = new DefaultHttpClient();
- HttpResponse response = httpclient.execute(httppost);
- return readStream(response.getEntity().getContent());
- }
-
-
-
-
-
-
-
- public static byte[] post(String path, Map<String, String> params, String encode) throws Exception{
-
- StringBuilder parambuilder = new StringBuilder("");
- if(params!=null && !params.isEmpty()){
- for(Map.Entry<String, String> entry : params.entrySet()){
- parambuilder.append(entry.getKey()).append("=")
- .append(URLEncoder.encode(entry.getValue(), encode)).append("&");
- }
- parambuilder.deleteCharAt(parambuilder.length()-1);
- }
- byte[] data = parambuilder.toString().getBytes();
- URL url = new URL(path);
- HttpURLConnection conn = (HttpURLConnection)url.openConnection();
- conn.setDoOutput(true);
- conn.setUseCaches(false);
- conn.setConnectTimeout(5 * 1000);
- conn.setRequestMethod("POST");
-
- conn.setRequestProperty("Accept", "image/gif, image/jpeg, image/pjpeg, image/pjpeg, application/x-shockwave-flash, application/xaml+xml, application/vnd.ms-xpsdocument, application/x-ms-xbap, application/x-ms-application, application/vnd.ms-excel, application/vnd.ms-powerpoint, application/msword, */*");
- conn.setRequestProperty("Accept-Language", "zh-CN");
- conn.setRequestProperty("User-Agent", "Mozilla/4.0 (compatible; MSIE 8.0; Windows NT 5.2; Trident/4.0; .NET CLR 1.1.4322; .NET CLR 2.0.50727; .NET CLR 3.0.04506.30; .NET CLR 3.0.4506.2152; .NET CLR 3.5.30729)");
- conn.setRequestProperty("Content-Type", "application/x-www-form-urlencoded");
- conn.setRequestProperty("Content-Length", String.valueOf(data.length));
- conn.setRequestProperty("Connection", "Keep-Alive");
-
-
- DataOutputStream outStream = new DataOutputStream(conn.getOutputStream());
- outStream.write(data);
- outStream.flush();
- outStream.close();
- if(conn.getResponseCode()==200){
- return readStream(conn.getInputStream());
- }
- return null;
- }
-
- /**
- * 读取流
- * @param inStream
- * @return 字节数组
- * @throws Exception
- */
- public static byte[] readStream(InputStream inStream) throws Exception{
- ByteArrayOutputStream outSteam = new ByteArrayOutputStream();
- byte[] buffer = new byte[1024];
- int len = -1;
- while( (len=inStream.read(buffer)) != -1){
- outSteam.write(buffer, 0, len);
- }
- outSteam.close();
- inStream.close();
- return outSteam.toByteArray();
- }
- }
4:MainActivity
- package cn.itcast.uploaddata;
-
- import java.io.File;
- import java.util.HashMap;
- import java.util.Map;
-
- import cn.itcast.net.HttpRequest;
- import cn.itcast.utils.FormFile;
- import cn.itcast.utils.SocketHttpRequester;
- import android.app.Activity;
- import android.os.Bundle;
- import android.os.Environment;
- import android.util.Log;
- import android.view.View;
- import android.widget.Button;
- import android.widget.EditText;
- import android.widget.Toast;
-
- public class MainActivity extends Activity {
- private static final String TAG = "MainActivity";
- private EditText timelengthText;
- private EditText titleText;
- private EditText videoText;
-
- @Override
- public void onCreate(Bundle savedInstanceState) {
- super.onCreate(savedInstanceState);
- setContentView(R.layout.main);
-
- Button button = (Button) this.findViewById(R.id.button);
- timelengthText = (EditText) this.findViewById(R.id.timelength);
- videoText = (EditText) this.findViewById(R.id.video);
- titleText = (EditText) this.findViewById(R.id.title);
- button.setOnClickListener(new View.OnClickListener() {
- @Override
- public void onClick(View v) {
- String title = titleText.getText().toString();
- String timelength = timelengthText.getText().toString();
- Map<String, String> params = new HashMap<String, String>();
- params.put("method", "save");
- params.put("title", title);
- params.put("timelength", timelength);
- try {
-
- File uploadFile = new File(Environment.getExternalStorageDirectory(), videoText.getText().toString());
- FormFile formfile = new FormFile("02.mp3", uploadFile, "video", "audio/mpeg");
- SocketHttpRequester.post("http://192.168.1.100:8080/videoweb/video/manage.do", params, formfile);
- Toast.makeText(MainActivity.this, R.string.success, 1).show();
- } catch (Exception e) {
- Toast.makeText(MainActivity.this, R.string.error, 1).show();
- Log.e(TAG, e.toString());
- }
- }
- });
-
- }
- }
5:AndroidManifest.xml
- <?xml version="1.0" encoding="utf-8" ?>
- - <manifest xmlns:android="http://schemas.android.com/apk/res/android" package="cn.itcast.uploaddata" android:versionCode="1" android:versionName="1.0">
- - <application android:icon="@drawable/icon" android:label="@string/app_name">
- <uses-library android:name="android.test.runner" />
- - <activity android:name=".MainActivity" android:label="@string/app_name">
- - <intent-filter>
- <action android:name="android.intent.action.MAIN" />
- <category android:name="android.intent.category.LAUNCHER" />
- </intent-filter>
- </activity>
- </application>
- <uses-sdk android:minSdkVersion="8" />
- -
-
- <uses-permission android:name="android.permission.MOUNT_UNMOUNT_FILESYSTEMS" />
- -
-
- <uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE" />
- -
-
- <uses-permission android:name="android.permission.INTERNET" />
- <instrumentation android:name="android.test.InstrumentationTestRunner" android:targetPackage="cn.itcast.uploaddata" android:label="Tests for My App" />
- </manifest>
分享到:
相关推荐
在Android应用开发中,将附件(如图片文件)上传到服务器是常见的功能需求。这个场景通常涉及到网络通信,特别是HTTP协议的使用。本篇将详细讲解如何在Android中实现图片文件的HTTP上传。 首先,我们需要了解HTTP...
总之,Android文件上传涉及到Android的文件操作、HTTP请求、服务器端交互以及UI控件的使用。通过合理利用现有的库和工具,可以高效实现这一功能。在实际开发中,注意处理网络异常、权限问题以及用户界面的优化,确保...
教程名称:老罗Android开发视频教程汇总课程目录:【】android之http协议编程第1集:http协议的介绍【】android之http协议编程第2集:http协议GET方式获取图片【】android之http协议编程第3集:使用Post方式进行提交...
在Android开发中,WebView是一个非常重要的组件,它允许我们在应用程序中内嵌网页,提供类似浏览器的体验。"webview附件"这个主题主要涉及到如何在WebView中处理文件下载,特别是附件的下载。以下将详细讲解这一知识...
在Android平台上,文件上传是一项常见的任务,特别是在开发涉及用户数据交互的应用时,如社交媒体应用、云存储服务等。本教程将深入探讨如何在Android客户端实现文件及文件夹上传,并介绍服务器端的相关处理。附件中...
webView.loadUrl("http://www.example.com"); ``` 这个简单的例子加载了一个网页到WebView中。然而,当用户在WebView中选中文本时,系统会默认显示一个标准的文本选择弹框,通常包括复制、剪切、粘贴等选项。但有时...
这个方法通常涉及HTTP请求,使用`HttpURLConnection`或第三方库如OkHttp,通过POST请求将图片文件作为请求体发送。同时,需要处理上传过程中的错误,如超时、网络中断等,确保上传的可靠性。 6. **异步处理**:为了...
本附件为下载地址,不是附件本身,基于osg最新版3.2.1rc1(http://www.openscenegraph.org/index.php/download-section/stable-releases/149-openscenegraph-3-2-1-release-candidate-1),基本android2.3版本编译。...
在Android平台上,从网络获取图片并将其作为附件发送到电子邮件是一项常见的任务,涉及到网络请求、图片处理、邮件API以及附件管理等多个技术环节。下面将详细解释这个过程中的关键知识点。 首先,从网络获取图片...
只是要注意,需要导入-v4.jar包,并且VerticalViewPagerCompat.java一定要放在android.support.v4.view包中,具体见附件。 用法同ViewPager几乎一样,只要设定 viewPager.setOrientation...
Email应用可以处理附件,支持多种文件格式,如文本、图片、PDF等。源码中包含解析和编码解码的逻辑,如Base64编码、MIME类型识别等。 8. **通知与推送**: 当有新邮件到达时,应用会通过NotificationManager展示...
提及的博客附件可能包含了详细的使用教程、示例代码以及作者在开发过程中遇到的问题和解决方案,对于学习和使用FinestWebView-Android非常有帮助。建议开发者参考博客内容,以更好地理解和利用这个库。 7. **适用...
Android的多媒体框架可以帮助处理这些附件,对于不常见的文件类型,可能需要第三方库支持。 9. **推送通知**: 实现新邮件即时提醒,可以借助Google的Firebase Cloud Messaging (FCM)服务,通过服务端向客户端发送...
综上所述,开发一个Android邮箱客户端涵盖了界面设计、网络编程(HTTP/SMTP/SSL/TLS)、数据库管理、Content Provider、Base64编码、邮件协议(IMAP/POP3/MIME)等多个技术领域,对开发者的技术广度和深度都有较高...
4. **数据存储与网络通信**:介绍如何在Android应用中使用SQLite数据库存储数据,以及如何使用HTTP协议进行网络请求,实现数据的同步和交换。 5. **多媒体与传感器支持**:讲解如何集成音频、视频和图像处理功能,...
资源名称:快速开发Android App 集成时下热门第三方SDK及框架教程内容:【】1-1 课程介绍—功能技术点和课程安排 19_03_46【】1-2 解开面纱—完整项目演示 19_11_23【】1-3 准备工作—项目架构部署 19_24_21【】1-4 ...
在Android平台上实现后台自动发送邮件的功能,通常需要借助一些特定的库文件,这些库文件以Java Archive (JAR)格式存在。在这个场景中,我们有三个关键的JAR包:mail.jar、activation.jar和additionnal.jar。这些JAR...
很好的一本android开发书籍,纵多的实例教程,可以快速提升开发能力,本材料附有书籍和源码,由于附件较大,一次不能传送全部,共分三个文件,这是第三部分,请同时下载三个文件,解压即可使用,希望对热爱android...
android HttpClient访问某些Https时,出现了问题,无法访问,好像是要安全验证。此Demo解决了此问题,HttpClient能够Https和Http类型的URL了。 在eclipse下打开工程若有乱码,请把eclipse的字符编码改成UTF-8。
- **HTTP/HTTPS请求**:使用HttpURLConnection或OkHttp库进行网络请求。 - **JSON解析**:Gson或Jackson库用于解析服务器返回的JSON数据。 4. **SMTP/IMAP协议**: - **SMTP (Simple Mail Transfer Protocol)**...