《2022年java文件上传,客户端和服务器端 .pdf》由会员分享,可在线阅读,更多相关《2022年java文件上传,客户端和服务器端 .pdf(12页珍藏版)》请在taowenge.com淘文阁网|工程机械CAD图纸|机械工程制图|CAD装配图下载|SolidWorks_CaTia_CAD_UG_PROE_设计图分享下载上搜索。
1、package com.gem.hsx.servlet;import java.io.File;import java.io.FileOutputStream;import java.io.IOException;import java.io.InputStream;import java.io.PrintWriter;import java.util.List;import java.util.UUID;import javax.servlet.ServletException;import javax.servlet.http.HttpServlet;import javax.servle
2、t.http.HttpServletRequest;import javax.servlet.http.HttpServletResponse;import mons.fileupload.FileItem;import mons.fileupload.FileItemFactory;import mons.fileupload.disk.DiskFileItemFactory;import mons.fileupload.servlet.ServletFileUpload;public class UploadServlet extends HttpServlet SuppressWarni
3、ngs(unchecked)protected void service(HttpServletRequest request,HttpServletResponse response)throws ServletException,IOException String BOUNDARY=UUID.randomUUID().toString();try request.setCharacterEncoding(UTF-8);/设置处理请求参数的编码格式response.setContentType(text/html;charset=UTF-8);/设置 Content-Type 字段值Pri
4、ntWriter out=response.getWriter();out.println(文件开始!);/下面的代码开始使用Commons-UploadFile 组件处理上传的文件数据FileItemFactory factory=new DiskFileItemFactory();/建立 FileItemFactory 对象ServletFileUpload upload=new ServletFileUpload(factory);/分析请求,并得到上传文件的FileItem 对象List items=upload.parseRequest(request);/从 web.xml 文件中
5、的参数中得到上传文件的路径String uploadPath=d:upload;File file=new File(uploadPath);名师资料总结-精品资料欢迎下载-名师精心整理-第 1 页,共 12 页 -if(!file.exists()file.mkdir();String filename=;/上传文件保存到服务器的文件名InputStream is=null;/当前上传文件的InputStream 对象/循环处理上传文件for(FileItem item:items)/处理普通的表单域if(item.isFormField()if(item.getFieldName().eq
6、uals(filename)/如果新文件不为空,将其保存在filename 中if(!item.getString().equals()filename=item.getString(UTF-8);/处理上传文件else if(item.getName()!=null&!item.getName().equals()/从客户端发送过来的上传文件路径中截取文件名filename=item.getName().substring(item.getName().lastIndexOf()+1);is=item.getInputStream();/得到上传文件的InputStream 对象 /将路径和
7、上传文件名组合成完整的服务端路径filename=uploadPath+BOUNDARY+filename;/如果服务器已经存在和上传文件同名的文件,则输出提示信息if(new File(filename).exists()new File(filename).delete();/开始上传文件if(!filename.equals()/用 FileOutputStream 打开服务端的上传文件FileOutputStream fos=new FileOutputStream(filename);byte buffer=new byte8192;/每次读 8K 字节int count=0;/开始
8、读取上传文件的字节,并将其输出到服务端的上传文件输出流中while(count=is.read(buffer)0)名师资料总结-精品资料欢迎下载-名师精心整理-第 2 页,共 12 页 -fos.write(buffer,0,count);/向服务端文件写入字节流 fos.close();/关闭 FileOutputStream 对象is.close();/InputStream 对象out.println(文件上传成功!);catch(Exception e)名师资料总结-精品资料欢迎下载-名师精心整理-第 3 页,共 12 页 -package com.gem.hsx.activity;i
9、mport java.io.File;import java.util.ArrayList;import java.util.HashMap;import java.util.List;import java.util.Map;import android.app.ListActivity;import android.content.Context;import android.content.Intent;import .Uri;import android.os.Bundle;import android.util.Log;import android.view.Display;impo
10、rt android.view.LayoutInflater;import android.view.View;import android.view.ViewGroup;import android.view.WindowManager;import android.view.WindowManager.LayoutParams;import android.widget.BaseAdapter;import android.widget.ImageView;import android.widget.ListView;import android.widget.TextView;impor
11、t com.gem.hsx.activity.R;public class ExDialog extends ListActivity private ListMap mData;private String mDir=/sdcard;Override protected void onCreate(Bundle savedInstanceState)super.onCreate(savedInstanceState);Intent intent=this.getIntent();Bundle bl=intent.getExtras();String title=bl.getString(ex
12、plorer_title);Uri uri=intent.getData();mDir=uri.getPath();setTitle(title);mData=getData();名师资料总结-精品资料欢迎下载-名师精心整理-第 4 页,共 12 页 -MyAdapter adapter=new MyAdapter(this);setListAdapter(adapter);WindowManager m=getWindowManager();Display d=m.getDefaultDisplay();LayoutParams p=getWindow().getAttributes();p
13、.height=(int)(d.getHeight()*0.8);p.width=(int)(d.getWidth()*0.95);getWindow().setAttributes(p);private ListMap getData()ListMap list=new ArrayListMap();Map map=null;File f=new File(mDir);File files=f.listFiles();if(!mDir.equals(/sdcard)map=new HashMap();map.put(title,返回上一级目录/);map.put(info,f.getPare
14、nt();map.put(img,R.drawable.ex_folder);list.add(map);if(files!=null)for(int i=0;i files.length;i+)map=new HashMap();map.put(title,filesi.getName();map.put(info,filesi.getPath();if(filesi.isDirectory()map.put(img,R.drawable.ex_folder);else map.put(img,R.drawable.ex_doc);list.add(map);return list;Over
15、ride protected void onListItemClick(ListView l,View v,int position,long id)Log.d(MyListView4-click,(String)mData.get(position).get(info);if(Integer)mData.get(position).get(img)=R.drawable.ex_folder)mDir=(String)mData.get(position).get(info);名师资料总结-精品资料欢迎下载-名师精心整理-第 5 页,共 12 页 -mData=getData();MyAdap
16、ter adapter=new MyAdapter(this);setListAdapter(adapter);else finishWithResult(String)mData.get(position).get(info);public final class ViewHolder public ImageView img;public TextView title;public TextView info;public class MyAdapter extends BaseAdapter private LayoutInflater mInflater;public MyAdapte
17、r(Context context)this.mInflater=LayoutInflater.from(context);public int getCount()return mData.size();public Object getItem(int arg0)return null;public long getItemId(int arg0)return 0;public View getView(int position,View convertView,ViewGroup parent)ViewHolder holder=null;if(convertView=null)hold
18、er=new ViewHolder();convertView=mInflater.inflate(R.layout.listview,null);holder.img=(ImageView)convertView.findViewById(R.id.img);holder.title=(TextView)convertView.findViewById(R.id.title);/holder.info=(TextView)convertView.findViewById(R.id.info);convertView.setTag(holder);else holder=(ViewHolder
19、)convertView.getTag();名师资料总结-精品资料欢迎下载-名师精心整理-第 6 页,共 12 页 -holder.img.setBackgroundResource(Integer)mData.get(position).get(img);holder.title.setText(String)mData.get(position).get(title);/holder.info.setText(String)mData.get(position).get(info);return convertView;private void finishWithResult(Strin
20、g path)Bundle conData=new Bundle();conData.putString(results,Thanks Thanks);Intent intent=new Intent();intent.putExtras(conData);Uri startDir=Uri.fromFile(new File(path);intent.setDataAndType(startDir,vnd.android.cursor.dir/lysesoft.andexplorer.file);setResult(RESULT_OK,intent);finish();package com.
21、gem.hsx.activity;import java.io.File;import com.gem.hsx.util.UploadUtil;import android.app.Activity;import android.app.ProgressDialog;import android.content.Intent;import .Uri;import android.os.Bundle;import android.os.Handler;import android.os.Message;import android.view.View;import android.view.Vi
22、ew.OnClickListener;import android.widget.Button;import android.widget.TextView;名师资料总结-精品资料欢迎下载-名师精心整理-第 7 页,共 12 页 -public class UpFile3Activity extends Activity private static final int REQUEST_EX=1;private String requestURL=http:/10.110.5.38:8080/UpFile1/UploadServlet;private Button up;String file
23、path;ProgressDialog p;Override public void onCreate(Bundle savedInstanceState)super.onCreate(savedInstanceState);setContentView(R.layout.main);Button button=(Button)findViewById(R.id.button);up=(Button)findViewById(R.id.up);button.setOnClickListener(new View.OnClickListener()public void onClick(View
24、 v)Intent intent=new Intent();intent.putExtra(explorer_title,getString(R.string.dialog_read_from_dir);intent.setDataAndType(Uri.fromFile(new File(/sdcard),*/*);intent.setClass(UpFile3Activity.this,ExDialog.class);startActivityForResult(intent,REQUEST_EX););up.setOnClickListener(new UpOnclick();prote
25、cted void onActivityResult(int requestCode,int resultCode,Intent intent)if(resultCode=RESULT_OK)if(requestCode=REQUEST_EX)Uri uri=intent.getData();TextView text=(TextView)findViewById(R.id.text);text.setText(文件路径为 +uri);filepath=uri.toString().substring(6);System.out.println(filepath);private class
26、UpOnclick implements OnClickListener 名师资料总结-精品资料欢迎下载-名师精心整理-第 8 页,共 12 页 -public void onClick(View v)p=new ProgressDialog(UpFile3Activity.this);p.setTitle(上传中);p.setMessage(正在上传,请等待);p.show();new Thread(new Runnable()public void run()File file=new File(filepath);UploadUtil uploadUtil=new UploadUtil(
27、);uploadUtil.uploadFile(file,requestURL);Message message=new Message();message.obj=上传完成;handler.sendMessage(message);).start();Handler handler=new Handler()Override public void handleMessage(Message msg)System.out.println(msg.toString();p.dismiss();super.handleMessage(msg);package com.gem.hsx.util;i
28、mport java.io.DataOutputStream;import java.io.File;import java.io.FileInputStream;import java.io.IOException;名师资料总结-精品资料欢迎下载-名师精心整理-第 9 页,共 12 页 -import java.io.InputStream;import .HttpURLConnection;import .MalformedURLException;import .URL;import java.util.UUID;import android.util.Log;/*上传工具类*autho
29、r spring sky*/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 String uploadFile(File file,String Requ
30、estURL)String result=null;String BOUNDARY=UUID.randomUUID().toString();/边界标识随机生成String PREFIX=-,LINE_END=rn;String CONTENT_TYPE=multipart/form-data;/内容类型try URL url=new URL(RequestURL);HttpURLConnection conn=(HttpURLConnection)url.openConnection();conn.setReadTimeout(TIME_OUT);conn.setConnectTimeout
31、(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);名师
32、资料总结-精品资料欢迎下载-名师精心整理-第 10 页,共 12 页 -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 是文件的名字,包含后缀名的比
33、如:abc.png*/sb.append(Content-Disposition:form-data;name=img;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 byte1024;int len=0;
34、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)/名师资料总结-精品资料欢迎下
35、载-名师精心整理-第 11 页,共 12 页 -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;名师资料总结-精品资料欢迎下载-名师精心整理-第 12 页,共 12 页 -