android上传图片至服务器=

合集下载

Android上传文件到服务端并显示进度条

Android上传文件到服务端并显示进度条

Android上传⽂件到服务端并显⽰进度条最近在做上传⽂件的服务,简单看了⽹上的教程。

结合实践共享出代码。

由于⽹上的⼤多数没有服务端的代码,这可不⾏呀,没服务端怎么调试呢。

Ok,先上代码。

Android 上传⽐较简单,主要⽤到的是 HttpURLConnection 类,然后加⼀个进度条组件。

private ProgressBar mPgBar;class UploadTask extends AsyncTask<Object,Integer,Void>{private DataOutputStream outputStream = null;private String fileName;private String uri;private String mLineEnd = "\r\n";private String mTwoHyphens = "--";private String boundary = "*****";File uploadFile ;long mTtotalSize ; // Get size of file, bytespublic UploadTask(String fileName,String uri){this.fileName = fileName;this.uri = uri;uploadFile= new File(fileName);mTtotalSize = uploadFile.length();}/*** 开始上传⽂件* @param objects* @return*/@Overrideprotected Void doInBackground(Object... objects) {long length = 0;int mBytesRead, mbytesAvailable, mBufferSize;byte[] buffer;int maxBufferSize = 256 * 1024;// 256KBtry{FileInputStream fileInputStream = new FileInputStream(new File(fileName));URL url = new URL(uri);HttpURLConnection con = (HttpURLConnection) url.openConnection();//如果有必要则可以设置Cookie// conn.setRequestProperty("Cookie","JSESSIONID="+cookie);// Set size of every block for postcon.setChunkedStreamingMode(256 * 1024);// 256KB// Allow Inputs & Outputscon.setDoInput(true);con.setDoOutput(true);con.setUseCaches(false);// Enable POST methodcon.setRequestMethod("POST");con.setRequestProperty("Connection", "Keep-Alive");con.setRequestProperty("Charset", "UTF-8");con.setRequestProperty("Content-Type","multipart/form-data;boundary=" + boundary);outputStream = new DataOutputStream(con.getOutputStream());outputStream.writeBytes(mTwoHyphens + boundary + mLineEnd);outputStream.writeBytes("Content-Disposition: form-data; name=\"file\"; filename=\"" + fileName + "\"" + mLineEnd);outputStream.writeBytes("Content-Type:application/octet-stream \r\n");outputStream.writeBytes(mLineEnd);mbytesAvailable = fileInputStream.available();mBufferSize = Math.min(mbytesAvailable, maxBufferSize);buffer = new byte[mBufferSize];// Read filemBytesRead = fileInputStream.read(buffer, 0, mBufferSize);while (mBytesRead > 0) {outputStream.write(buffer, 0, mBufferSize);length += mBufferSize;publishProgress((int) ((length * 100) / mTtotalSize));mbytesAvailable = fileInputStream.available();mBufferSize = Math.min(mbytesAvailable, maxBufferSize);mBytesRead = fileInputStream.read(buffer, 0, mBufferSize);}outputStream.writeBytes(mLineEnd);outputStream.writeBytes(mTwoHyphens + boundary + mTwoHyphens+ mLineEnd);publishProgress(100);// Responses from the server (code and message)int serverResponseCode = con.getResponseCode();String serverResponseMessage = con.getResponseMessage();fileInputStream.close();outputStream.flush();outputStream.close();} catch (Exception ex) {ex.printStackTrace();Log.v(TAG,"uploadError");}return null;}@Overrideprotected void onProgressUpdate(Integer... progress) {mPgBar.setProgress(progress[0]);}}主要流程为继承AsyncTask,然后使⽤HttpURLConnection 去上传⽂件。

Android使用post方式上传图片到服务器的方法

Android使用post方式上传图片到服务器的方法

Android使⽤post⽅式上传图⽚到服务器的⽅法本⽂实例讲述了Android使⽤post⽅式上传图⽚到服务器的⽅法。

分享给⼤家供⼤家参考,具体如下:/*** 上传⽂件到服务器类** @author tom*/public class UploadUtil {private static final String TAG = "uploadFile";private static final int TIME_OUT = 10 * 1000; // 超时时间private static final String CHARSET = "utf-8"; // 设置编码/*** Android上传⽂件到服务端** @param file 需要上传的⽂件* @param RequestURL 请求的rul* @return 返回响应的内容*/public static String uploadFile(File file, String RequestURL) {String result = null;String BOUNDARY = UUID.randomUUID().toString(); // 边界标识随机⽣成String PREFIX = "--", LINE_END = "\r\n";String CONTENT_TYPE = "multipart/form-data"; // 内容类型try {URL url = new URL(RequestURL);HttpURLConnection conn = (HttpURLConnection) url.openConnection();conn.setReadTimeout(TIME_OUT);conn.setConnectTimeout(TIME_OUT);conn.setDoInput(true); // 允许输⼊流conn.setDoOutput(true); // 允许输出流conn.setUseCaches(false); // 不允许使⽤缓存conn.setRequestMethod("POST"); // 请求⽅式conn.setRequestProperty("Charset", CHARSET); // 设置编码conn.setRequestProperty("connection", "keep-alive");conn.setRequestProperty("Content-Type", CONTENT_TYPE + ";boundary=" + BOUNDARY);if (file != null) {/*** 当⽂件不为空,把⽂件包装并且上传*/DataOutputStream dos = new DataOutputStream(conn.getOutputStream());StringBuffer sb = new StringBuffer();sb.append(PREFIX);sb.append(BOUNDARY);sb.append(LINE_END);/*** 这⾥重点注意: name⾥⾯的值为服务端需要key 只有这个key 才可以得到对应的⽂件* filename是⽂件的名字,包含后缀名的⽐如:abc.png*/sb.append("Content-Disposition: form-data; name=\"uploadfile\"; filename=\""+ file.getName() + "\"" + LINE_END);sb.append("Content-Type: application/octet-stream; charset=" + CHARSET + LINE_END);sb.append(LINE_END);dos.write(sb.toString().getBytes());InputStream is = new FileInputStream(file);byte[] bytes = new byte[1024];int len = 0;while ((len = is.read(bytes)) != -1) {dos.write(bytes, 0, len);}is.close();dos.write(LINE_END.getBytes());byte[] end_data = (PREFIX + BOUNDARY + PREFIX + LINE_END).getBytes();dos.write(end_data);dos.flush();/*** 获取响应码 200=成功当响应成功,获取响应的流*/int res = conn.getResponseCode();Log.e(TAG, "response code:" + res);// if(res==200)// {Log.e(TAG, "request success");InputStream input = conn.getInputStream();StringBuffer sb1 = new StringBuffer();int ss;while ((ss = input.read()) != -1) {sb1.append((char) ss);}result = sb1.toString();Log.e(TAG, "result : " + result);// }// else{// Log.e(TAG, "request error");// }}} catch (MalformedURLException e) {e.printStackTrace();} catch (IOException e) {e.printStackTrace();}return result;}/*** 通过拼接的⽅式构造请求内容,实现参数传输以及⽂件传输** @param url Service net address* @param params text content* @param files pictures* @return String result of Service response* @throws IOException*/public static String post(String url, Map<String, String> params, Map<String, File> files)throws IOException {String BOUNDARY = java.util.UUID.randomUUID().toString();String PREFIX = "--", LINEND = "\r\n";String MULTIPART_FROM_DATA = "multipart/form-data";String CHARSET = "UTF-8";URL uri = new URL(url);HttpURLConnection conn = (HttpURLConnection) uri.openConnection();conn.setReadTimeout(10 * 1000); // 缓存的最长时间conn.setDoInput(true);// 允许输⼊conn.setDoOutput(true);// 允许输出conn.setUseCaches(false); // 不允许使⽤缓存conn.setRequestMethod("POST");conn.setRequestProperty("connection", "keep-alive");conn.setRequestProperty("Charsert", "UTF-8");conn.setRequestProperty("Content-Type", MULTIPART_FROM_DATA + ";boundary=" + BOUNDARY); // ⾸先组拼⽂本类型的参数StringBuilder sb = new StringBuilder();for (Map.Entry<String, String> entry : params.entrySet()) {sb.append(PREFIX);sb.append(BOUNDARY);sb.append(LINEND);sb.append("Content-Disposition: form-data; name=\"" + entry.getKey() + "\"" + LINEND);sb.append("Content-Type: text/plain; charset=" + CHARSET + LINEND);sb.append("Content-Transfer-Encoding: 8bit" + LINEND);sb.append(LINEND);sb.append(entry.getValue());sb.append(LINEND);}DataOutputStream outStream = new DataOutputStream(conn.getOutputStream());outStream.write(sb.toString().getBytes());// 发送⽂件数据if (files != null)for (Map.Entry<String, File> file : files.entrySet()) {StringBuilder sb1 = new StringBuilder();sb1.append(PREFIX);sb1.append(BOUNDARY);sb1.append(LINEND);sb1.append("Content-Disposition: form-data; name=\"uploadfile\"; filename=\""+ file.getValue().getName() + "\"" + LINEND);sb1.append("Content-Type: application/octet-stream; charset=" + CHARSET + LINEND);sb1.append(LINEND);outStream.write(sb1.toString().getBytes());InputStream is = new FileInputStream(file.getValue());byte[] buffer = new byte[1024];int len = 0;while ((len = is.read(buffer)) != -1) {outStream.write(buffer, 0, len);}is.close();outStream.write(LINEND.getBytes());}// 请求结束标志byte[] end_data = (PREFIX + BOUNDARY + PREFIX + LINEND).getBytes();outStream.write(end_data);outStream.flush();// 得到响应码int res = conn.getResponseCode();InputStream in = conn.getInputStream();StringBuilder sb2 = new StringBuilder();if (res == 200) {int ch;while ((ch = in.read()) != -1) {sb2.append((char) ch);}}outStream.close();conn.disconnect();return sb2.toString();}}⽰例调⽤第⼆种⽅式上传:final Map<String, String> params = new HashMap<String, String>();params.put("send_userId", String.valueOf(id));params.put("send_email", address);params.put("send_name", name);params.put("receive_email", emails);final Map<String, File> files = new HashMap<String, File>();files.put("uploadfile", file);final String request = UploadUtil.post(requestURL, params, files);更多关于Android相关内容感兴趣的读者可查看本站专题:《》、《》、《》、《》、《》、《》及《》希望本⽂所述对⼤家Android程序设计有所帮助。

android传送照片到FTP服务器的实现代码

android传送照片到FTP服务器的实现代码

android传送照⽚到FTP服务器的实现代码本⽂实例为⼤家分享了android传送照⽚到FTP服务器的具体代码,供⼤家参考,具体内容如下在安卓环境下可以使⽤,在java环境下也可以使⽤,本⼈先在Java环境下实现了功能,然后移植到了安卓⼿机上,其它都是⼀样的。

package com.photo;import java.io.File;import java.io.FileInputStream;import java.io.FileNotFoundException;import java.io.IOException;import java.io.InputStream;import .ftp.FTPClient;import .ftp.FTPReply;public class FileTool {/*** Description: 向FTP服务器上传⽂件** @param url* FTP服务器hostname* @param port* FTP服务器端⼝* @param username* FTP登录账号* @param password* FTP登录密码* @param path* FTP服务器保存⽬录,是linux下的⽬录形式,如/photo/* @param filename* 上传到FTP服务器上的⽂件名,是⾃⼰定义的名字,* @param input* 输⼊流* @return 成功返回true,否则返回false*/public static boolean uploadFile(String url, int port, String username,String password, String path, String filename, InputStream input) {boolean success = false;FTPClient ftp = new FTPClient();try {int reply;ftp.connect(url, port);// 连接FTP服务器// 如果采⽤默认端⼝,可以使⽤ftp.connect(url)的⽅式直接连接FTP服务器ftp.login(username, password);//登录reply = ftp.getReplyCode();if (!FTPReply.isPositiveCompletion(reply)) {ftp.disconnect();return success;}ftp.changeWorkingDirectory(path);ftp.storeFile(filename, input);input.close();ftp.logout();success = true;} catch (IOException e) {e.printStackTrace();} finally {if (ftp.isConnected()) {try {ftp.disconnect();} catch (IOException ioe) {}}}return success;}// 测试public static void main(String[] args) {FileInputStream in = null ;File dir = new File("G://pathnew");File files[] = dir.listFiles();if(dir.isDirectory()) {for(int i=0;i<files.length;i++) {try {in = new FileInputStream(files[i]);boolean flag = uploadFile("17.8.119.77", 21, "android", "android","/photo/", "412424123412341234_20130715120334_" + i + ".jpg", in);System.out.println(flag);} catch (FileNotFoundException e) {e.printStackTrace();}}}}}以上为java代码,下⾯是android代码。

Android实现上传图片功能

Android实现上传图片功能

Android实现上传图⽚功能本⽂实例为⼤家分享了Android实现上传图⽚功能的具体代码,供⼤家参考,具体内容如下设定拍照返回的图⽚路径/*** 设定拍照返回的图⽚路径* @param image 图⽚路径* @param i 约定值*/protected void image(String image, int i) {//创建file对象,⽤于存储拍照后的图⽚,这也是拍照成功后的照⽚路径outputImage = new File(getExternalCacheDir(),image);try {//判断⽂件是否存在,存在删除,不存在创建if (outputImage.exists()){outputImage.delete();}outputImage.createNewFile();} catch (IOException e) {e.printStackTrace();}//相机拍照返回图⽚路径Uri photoUri;//判断当前Android版本if(Build.VERSION.SDK_INT>=24){photoUri = FileProvider.getUriForFile(TextActivity.this,"包名.FileProvider",outputImage);}else {photoUri = Uri.fromFile(outputImage);}Intent intent = new Intent(MediaStore.ACTION_IMAGE_CAPTURE);intent.putExtra(MediaStore.EXTRA_OUTPUT, photoUri);startActivityForResult(intent, i);}调⽤系统相机拍照接受返回的图⽚路径@Overrideprotected void onActivityResult(int requestCode, int resultCode, Intent data) {super.onActivityResult(requestCode, resultCode, data);if (resultCode == RESULT_OK) {if (requestCode == IMAGE_Y) {getImageView(binding.imageY,"0");}if (requestCode == IMAGE_Q) {getImageView(binding.imageQ,"1");}}}上传图⽚/*** 上传图⽚* @param view 图⽚展⽰ view*/protected void getImageView(@NotNull ImageView view, String type) {Bitmap photo = BitmapFactory.decodeFile(outputImage.getAbsolutePath());view.setImageBitmap(photo);int direction = 0;try {ExifInterface exif = new ExifInterface(String.valueOf(outputImage));direction = Integer.parseInt(exif.getAttribute(ExifInterface.TAG_ORIENTATION));} catch (IOException e) {e.printStackTrace();}Matrix matrix = new Matrix();Uri uri = Uri.fromFile(outputImage);String f = uri.getPath();Bitmap b = rotateBitmap(getBitmapFromUrl(f,900,1200),0);switch (direction) {case 1:Log.d("图⽚⽅向","顶部,左侧(⽔平/正常)");b = rotateBitmap(getBitmapFromUrl(f,900,1200),0);break;case 2:b = rotateBitmap(getBitmapFromUrl(f,900,1200),0);Log.d("图⽚⽅向","顶部,右侧(⽔平镜像)");break;case 3:b = rotateBitmap(getBitmapFromUrl(f,900,1200),180);Log.d("图⽚⽅向","底部,右侧(旋转180)");break;case 4:matrix.postScale(1, -1);b = Bitmap.createBitmap(b,0,0,900,1200,matrix,true);Log.d("图⽚⽅向","底部,左侧(垂直镜像)");break;case 5:matrix.postScale(-1, 1);b = rotateBitmap(getBitmapFromUrl(f,900,1200),270);b = Bitmap.createBitmap(b,0,0,900,1200,matrix,true);Log.d("图⽚⽅向","左侧,顶部(⽔平镜像并顺时针旋转270)");break;case 6:b = rotateBitmap(getBitmapFromUrl(f,900,1200),90);Log.d("图⽚⽅向","右侧,顶部(顺时针旋转90)");break;case 7:matrix.postScale(-1, 1);b = rotateBitmap(getBitmapFromUrl(f,900,1200),90);b = Bitmap.createBitmap(b,0,0,900,1200,matrix,true);Log.d("图⽚⽅向","右侧,底部(⽔平镜像,顺时针旋转90度)");break;case 8:b = rotateBitmap(getBitmapFromUrl(f,900,1200),270);Log.d("图⽚⽅向","左侧,底部(顺时针旋转270)");break;default:break;}try {File files = new File(new URI(uri.toString()));saveBitmap(b,files);} catch (URISyntaxException e) {e.printStackTrace();}try {String file = uploadImage(networkApi.getFormal() + "setImage", uri.getPath(), code, userId);TextBase.FileInfo fileInfo = new TextBase.FileInfo();fileInfo.setFilePath(file);mFileInfos.add(fileInfo);model.load(file,type);} catch (IOException | JSONException e) {e.printStackTrace();}}/*** 上传图⽚* @param url 上传接⼝路径* @param imagePath 图⽚路径* @param code 唯⼀标识* @return 服务器图⽚的路径* @throws IOException* @throws JSONException*/public static String uploadImage(String url, String imagePath, String code, String userId) throws IOException, JSONException { OkHttpClient okHttpClient = new OkHttpClient();Log.d("imagePath", imagePath);File file = new File(imagePath);RequestBody image = RequestBody.create(MediaType.parse("image/jpg"), file);RequestBody requestBody = new MultipartBody.Builder().setType(MultipartBody.FORM).addFormDataPart("file", imagePath, image).addFormDataPart("fileOid", code).addFormDataPart("userId", userId).build();Request request = new Request.Builder().url(url).addHeader("Authorization",令牌).post(requestBody).build();Response response = okHttpClient.newCall(request).execute();JSONObject jsonObject = new JSONObject(response.body().string());return jsonObject.optString("msg");}其他⼯具类/*** 压缩图⽚的⽅法* @param url* @param width* @param height* @return*/public static Bitmap getBitmapFromUrl(String url, double width, double height) {BitmapFactory.Options options = new BitmapFactory.Options();options.inJustDecodeBounds = true; // 设置了此属性⼀定要记得将值设置为falseBitmap bitmap = BitmapFactory.decodeFile(url);// 防⽌OOM发⽣options.inJustDecodeBounds = false;int mWidth = bitmap.getWidth();int mHeight = bitmap.getHeight();Matrix matrix = new Matrix();float scaleWidth = 1;float scaleHeight = 1;// 按照固定宽⾼进⾏缩放if(mWidth <= mHeight) {scaleWidth = (float) (width/mWidth);scaleHeight = (float) (height/mHeight);} else {scaleWidth = (float) (height/mWidth);scaleHeight = (float) (width/mHeight);}// 按照固定⼤⼩对图⽚进⾏缩放matrix.postScale(scaleWidth, scaleHeight);Bitmap newBitmap = Bitmap.createBitmap(bitmap, 0, 0, mWidth, mHeight, matrix, true); // ⽤完了记得回收bitmap.recycle();return newBitmap;}/*** Android保存Bitmap到⽂件* @param bitmap* @param file* @return*/public static boolean saveBitmap(Bitmap bitmap, File file) {if (bitmap == null)return false;FileOutputStream fos = null;try {fos = new FileOutputStream(file);press(pressFormat.JPEG, 100, fos);fos.flush();return true;} catch (Exception e) {e.printStackTrace();} finally {if (fos != null) {try {fos.close();} catch (IOException e) {e.printStackTrace();}}}return false;}/*** 旋转图⽚* @param bitmap 图⽚* @param rotate ⾓度* @return*/public static Bitmap rotateBitmap(Bitmap bitmap, int rotate) {if (bitmap == null)return null;int w = bitmap.getWidth();int h = bitmap.getHeight();Matrix mtx = new Matrix();mtx.postRotate(rotate);return Bitmap.createBitmap(bitmap, 0, 0, w, h, mtx, true);}以上就是本⽂的全部内容,希望对⼤家的学习有所帮助,也希望⼤家多多⽀持。

Android通过Ksoap2链接WebService上传图片的功能

Android通过Ksoap2链接WebService上传图片的功能

以前开发java程序时导入jar包都是用一下的方法:工程点击右键->Build Path->Add Libraries->User Library->选择包含需要的jar包的Library(如果没有的话就点击User Libraries新建一个Library,然后再选中)但是,在Android中这样导入jar包会导致程序在模拟器中运行时抛出ng.NoClassDefFoundError异常,在Android中导入jar包的步骤如下:工程点击右键->Build Path->Add External Archives->选择要导入的jar包另外还有一个问题就是:Android模拟器访问Tomcat上部署的webservice程序时,不能用localhost或者本机IP,Android默认访问本机地址为10.0.2.2。

原因猜想对于产生上述NoClassDefFoundError的原因,查看一下工程中的classpath文件就可以找到。

如果是利用第一种方法导入的jar包的话,classpath文件中会生成这样一条语句:<classpathentry kind="con" path="ER_LIBRARY/KSOAP2"/>,这种导入jar包的方法依赖于开发环境eclipse;而如果用第二种方法导入jar包的话,会在classpath中产生如下的语句:<classpathentry kind="lib" path="D:/JAVATOOLS/ksoap2-android-assembly-2.5.2-jar-with- dependencies.jar"/>,这种导入方式是用的绝对路径,与eclipse开发环境无关,而且以这种方式导入后,jar包的信息会被加到工程class.dex中,进而会被打包到apk中。

Android客户端调用webService上传图片到服务器

Android客户端调用webService上传图片到服务器

Android客户端调用webService上传图片到服务器调用服务器的webservice接口,实现从Android上传图片到服务器,然后从服务器下载图片到Android客户端从Android端用io流读取到要上传的图片,用Base64编码成字节流的字符串,通过调用webservice把该字符串作为参数传到服务器端,服务端解码该字符串,最后保存到相应的路径下。

整个上传过程的关键就是以字节流的字符串进行数据传递。

下载过程,与上传过程相反,把服务器端和客户端的代码相应的调换1.客户端代码读取Android sdcard上的图片。

public void testUpload(){try{String srcUrl = "/sdcard/"; //路径String fileName = "aa.jpg"; //文件名FileInputStream fis = new FileInputStream(srcUrl + fileName);ByteArrayOutputStream baos = new ByteArrayOutputStream();byte[] buffer = new byte[1024];int count = 0;while((count = fis.read(buffer)) >= 0){baos.write(buffer, 0, count);}String uploadBuffer = new String(Base64.encode(baos.toByteArray())); //进行Base64编码String methodName = "uploadImage";connectWebService(methodName,fileName, uploadBuffer); //调用webserviceLog.i("connectWebService", "start");fis.close();}catch(Exception e){e.printStackTrace();}}connectWebService()方法://使用ksoap2 调用webserviceprivate boolean connectWebService(String methodName,String fileName, String imageBuffer) { String namespace = "http://134.192.44.105:8080/SSH2/service/IService";// 命名空间,即服务器端得接口,注:后缀没加.wsdl,//服务器端我是用x-fire实现webservice接口的String url = "http://134.192.44.105:8080/SSH2/service/IService";//对应的url//以下就是调用过程了,不明白的话请看相关webservice文档SoapObject soapObject = new SoapObject(namespace, methodName);soapObject.addProperty("filename", fileName); //参数1 图片名soapObject.addProperty("image", imageBuffer); //参数2 图片字符串SoapSerializationEnvelope envelope = new SoapSerializationEnvelope(SoapEnvelope.VER10);envelope.dotNet = false;envelope.setOutputSoapObject(soapObject);HttpTransportSE httpTranstation = new HttpTransportSE(url);try {httpTranstation.call(namespace, envelope);Object result = envelope.getResponse();Log.i("connectWebService", result.toString());} catch (Exception e) {e.printStackTrace();}return false;}2.服务端方法服务器端的webservice代码:public String uploadImage(String filename, String image) { FileOutputStream fos = null;try{String toDir = "C:\\Program Files\\T omcat 6.0\\webapps\\SSH2\\images";//存储路径byte[] buffer = new BASE64Decoder().decodeBuffer(image);//对Android传过来的图片字符串进行解码File destDir = new File(toDir);if(!destDir.exists()) destDir.mkdir();fos = new FileOutputStream(new File(destDir,filename));//保存图片fos.write(buffer);fos.flush();fos.close();return "上传图片成功!" + "图片路径为:" + toDir;}catch (Exception e){e.printStackTrace();}return "上传图片失败!";}。

android中文件上传

android中文件上传

在Android的客户端编程中(特别是SNS 类型的客户端),经常需要实现注册功能Activity,要用户输入用户名,密码,邮箱,照片后注册。

但这时就有一个问题,在HTML中用form 表单就能实现如上的注册表单,需要的信息会自动封装为完整的HTTP协议,但在Android 中如何把这些参数和需要上传的文件封装为HTTP协议呢?我们可以先做个试验,看一下form表单到底封装了什么样的信息。

第一步:编写一个Servlet,把接收到的HTTP信息保存在一个文件中,代码如下:1.2. public void doPost(HttpServletRequest request,HttpServletResponse response)3. throws ServletException, IOException {4. //获取输入流,是HTTP协议中的实体内容5. ServletInputStream sis=request.getInputStream();6.7. //缓冲区8. byte buffer[]=new byte[1024];9.10. FileOutputStream fos=new FileOutputStream("d:\\file.log");11.12. int len=sis.read(buffer, 0, 1024);13.14. //把流里的信息循环读入到file.log文件中15. while( len!=-1 )16. {17. fos.write(buffer, 0, len);18. len=sis.readLine(buffer, 0, 1024);19. }20.21. fos.close();22. sis.close();23.24. }25.第二步:实现如下一个表单页面,详细的代码如下:1.2.<form action="servlet/ReceiveFile" method="post"enctype="multipart/form-data>3.第一个参数<input type="text" name="name1"/><br/>4.第二个参数<input type="text" name="name2"/><br/>5.第一个上传的文件<input type="file" name="file1"/><br/>6.第二个上传的文件<input type="file" name="file2"/> <br/>7. <input type="submit" value="提交">8.</form>9.从表单源码可知,表单上传的数据有4个:参数name1和name2,文件file1和file2首先从file.log观察两个参数name1和name2的情况。

Android上传文件到服务器的方法

Android上传文件到服务器的方法

Android上传⽂件到服务器的⽅法本⽂实例为⼤家分享了Android端实现⽂件上传的具体代码,供⼤家参考,具体内容如下1)、新建⼀个Android项⽬命名为androidUpload,⽬录结构如下:2)、新建FormFile类,⽤来封装⽂件信息package com.ljq.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;}}3)、新建SocketHttpRequester类,封装上传⽂件到服务器代码package com.ljq.utils;import java.io.BufferedReader;import java.io.InputStreamReader;import java.io.OutputStream;import .InetAddress;import .Socket;import .URL;import java.util.Map;/*** 上传⽂件到服务器** @author Administrator**/public class SocketHttpRequester {/*** 直接通过HTTP协议提交数据到服务器,实现如下⾯表单提交功能:* <FORM METHOD=POST ACTION="http://192.168.1.101:8083/upload/servlet/UploadServlet" enctype="multipart/form-data"><INPUT TYPE="text" NAME="name"><INPUT TYPE="text" NAME="id"><input type="file" name="imagefile"/><input type="file" name="zip"/></FORM>* @param path 上传路径(注:避免使⽤localhost或127.0.0.1这样的路径测试,因为它会指向⼿机模拟器,你可以使⽤或http://192.168.1.101:8083这样的路径测试) * @param params 请求参数 key为参数名,value为参数值* @param file 上传⽂件*/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();//下⾯完成HTTP请求头的发送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.m 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());//写完HTTP请求头后根据HTTP协议再写⼀个回车换⾏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){//读取web服务器返回的数据,判断请求码是否为200,如果不是200,代表请求失败return false;}outStream.flush();outStream.close();reader.close();socket.close();return true;}/*** 提交数据到服务器* @param path 上传路径(注:避免使⽤localhost或127.0.0.1这样的路径测试,因为它会指向⼿机模拟器,你可以使⽤或http://192.168.1.10:8080这样的路径测试)* @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});}}4)、新建MainActivity类,实现每隔5秒上传⼀次package com.ljq.activity;import java.io.File;import java.util.HashMap;import java.util.Map;import android.app.Activity;import android.os.Bundle;import android.os.Environment;import android.os.Handler;import android.util.Log;import com.ljq.utils.FormFile;import com.ljq.utils.SocketHttpRequester;public class MainActivity extends Activity {private File file;private Handler handler;private static final String TAG="MainActivity";@Overridepublic void onCreate(Bundle savedInstanceState) {super.onCreate(savedInstanceState);setContentView(yout.main);Log.i(TAG, "onCreate");file = new File(Environment.getExternalStorageDirectory(), "123.rmvb");Log.i(TAG, "照⽚⽂件是否存在:"+file);handler=new Handler();handler.post(runnable);}Runnable runnable=new Runnable() {public void run() {Log.i(TAG, "runnable run");uploadFile(file);handler.postDelayed(runnable, 5000);}};/*** 上传图⽚到服务器** @param imageFile 包含路径*/public void uploadFile(File imageFile) {Log.i(TAG, "upload start");try {String requestUrl = "http://192.168.1.101:8083/upload/upload/execute.do";//请求普通信息Map<String, String> params = new HashMap<String, String>();params.put("username", "张三");params.put("pwd", "zhangsan");params.put("age", "21");params.put("fileName", imageFile.getName());//上传⽂件FormFile formfile = new FormFile(imageFile.getName(), imageFile, "image", "application/octet-stream"); SocketHttpRequester.post(requestUrl, params, formfile);Log.i(TAG, "upload success");} catch (Exception e) {Log.i(TAG, "upload error");e.printStackTrace();}Log.i(TAG, "upload end");}}5)、修改清单⽂件<?xml version="1.0" encoding="utf-8"?><manifest xmlns:android="/apk/res/android"package="com.ljq.activity"android:versionCode="1"android:versionName="1.0"><application android:icon="@drawable/icon" android:label="@string/app_name"><activity android:name=".MainActivity"android:label="@string/app_name"><intent-filter><action android:name="android.intent.action.MAIN" /><category android:name="UNCHER" /></intent-filter></activity></application><uses-sdk android:minSdkVersion="4" /><uses-permission android:name="android.permission.INTERNET" /></manifest>以上就是本⽂的全部内容,希望对⼤家的学习有所帮助,也希望⼤家多多⽀持。

  1. 1、下载文档前请自行甄别文档内容的完整性,平台不提供额外的编辑、内容补充、找答案等附加服务。
  2. 2、"仅部分预览"的文档,不可在线预览部分如存在完整性等问题,可反馈申请退款(可完整预览的文档不适用该条件!)。
  3. 3、如文档侵犯您的权益,请联系客服反馈,我们会尽快为您处理(人工客服工作时间:9:00-18:30)。

android上传图片至服务器本实例实现了android上传手机图片至服务器,服务器进行保存服务器servlet代码publicvoid doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {String temp=request.getSession().getServletContext().getRealPath("/") +"temp"; //临时目录System.out.println("temp="+temp);String loadpath=request.getSession().getServletContext().getRealPath(" /")+"Image"; //上传文件存放目录System.out.println("loadpath="+loadpath);DiskFileUpload fu =new DiskFileUpload();fu.setSizeMax(1*1024*1024); // 设置允许用户上传文件大小,单位:字节fu.setSizeThreshold(4096); // 设置最多只允许在内存中存储的数据,单位:字节fu.setRepositoryPath(temp); // 设置一旦文件大小超过getSizeThresh old()的值时数据存放在硬盘的目录//开始读取上传信息int index=0;List fileItems =null;try{fileItems = fu.parseRequest(reques t);System.out.println("fileItems="+fi leItems);} catch(Exception e) {e.printStackTrace();}Iterator iter = fileItems.iterator(); // 依次处理每个上传的文件while(iter.hasNext()){FileItem item = (FileItem)iter.next();// 忽略其他不是文件域的所有表单信息if(!item.isFormField()){String name = item.getName();//获取上传文件名,包括路径name=name.substring(stIndexOf("\\")+1);//从全路径中提取文件名long size = item.getSize();if((name==null||name.equals("")) && size==0)continue;int point = name.indexOf(".");name=(new Date()).getTime()+name.substring(point,name.le ngth())+index;index++;File fNew=new File(loadpath, name);try{item.write(fNew);} catch(Exception e) {// TODO Auto-generated catch bl ocke.printStackTrace();}}else//取出不是文件域的所有表单信息{String fieldvalue = item.getString();//如果包含中文应写为:(转为UTF-8编码)//String fieldvalue = new String(item.getString().getBytes(), "UTF-8");}}String text1="11";response.sendRedirect("result.jsp?text1="+ text1);}android客户端代码publicclass PhotoUpload extends Activity {private String newName ="image.jpg";private String uploadFile ="/sdcard/image.JPG";private String actionUrl ="http://192.168.0.71:8086/HelloWord/myForm";private TextView mText1;private TextView mText2;private Button mButton;@Overridepublicvoid onCreate(Bundle savedInstanceState){super.onCreate(savedInstanceState);setContentView(yout.photo_upload);mText1 = (TextView) findViewById(R.id.myText2);//"文件路径:\n"+mText1.setText(uploadFile);mText2 = (TextView) findViewById(R.id.myText3);//"上传网址:\n"+mText2.setText(actionUrl);/* 设置mButton的onClick事件处理*/mButton = (Button) findViewById(R.id.myButton);mButton.setOnClickListener(new View.OnClickListener(){publicvoid onClick(View v){uploadFile();}});}/* 上传文件至Server的方法*/privatevoid uploadFile(){String end ="\r\n";String twoHyphens ="--";String boundary ="*****";try{URL url =new URL(actionUrl);HttpURLConnection con=(HttpURLConnection)url.openConnection();/* 允许Input、Output,不使用Cache */con.setDoInput(true);con.setDoOutput(true);con.setUseCaches(false);/* 设置传送的method=POST */con.setRequestMethod("POST");/* setRequestProperty */con.setRequestProperty("Connection", "Keep-Alive");con.setRequestProperty("Charset", "UTF-8");con.setRequestProperty("Content-Type","multipart/form-data;boundary="+boundary);/* 设置DataOutputStream */DataOutputStream ds =new DataOutputStream(con.getOutputStream());ds.writeBytes(twoHyphens + boundary + end);ds.writeBytes("Content-Disposition: form-data; "+"name=\"file1\";filename=\""+newName +"\""+ end);ds.writeBytes(end);/* 取得文件的FileInputStream */FileInputStream fStream =new FileInputStream(uploadFile);/* 设置每次写入1024bytes */int bufferSize =1024;byte[] buffer =newbyte[bufferSize];int length =-1;/* 从文件读取数据至缓冲区*/while((length = fStream.read(buffer)) !=-1){/* 将资料写入DataOutputStream中*/ds.write(buffer, 0, length);}ds.writeBytes(end);ds.writeBytes(twoHyphens + boundary + twoHyphens + end);/* close streams */fStream.close();ds.flush();/* 取得Response内容*/InputStream is = con.getInputStream();int ch;StringBuffer b =new StringBuffer();while( ( ch = is.read() ) !=-1 ){b.append( (char)ch );}/* 将Response显示于Dialog */showDialog("上传成功"+b.toString().trim());/* 关闭DataOutputStream */ds.close();}catch(Exception e){showDialog("上传失败"+e);}}/* 显示Dialog的method */privatevoid showDialog(String mess){new AlertDialog.Builder(PhotoUpload.this).setTitle("Message").setMessage(mess).setNegativeButton("确定",new DialogInterface.OnClickListener() {publicvoid onClick(DialogInterface dialog, int which){}}).show();}}。

相关文档
最新文档