java 接收文件_HTTP接受文件的java实现

1 packageTOOLS;2

3 importjava.io.BufferedOutputStream;4 importjava.io.File;5 importjava.io.FileOutputStream;6 importjava.io.IOException;7 importjava.io.InputStream;8 importjava.io.OutputStream;9 importjava.util.HashMap;10 importjava.util.Map;11

12 importjavax.servlet.http.HttpServletRequest;13 importjavax.servlet.http.HttpServletResponse;14 importorg.apache.commons.fileupload.FileItemIterator;15 importorg.apache.commons.fileupload.FileItemStream;16 importorg.apache.commons.fileupload.FileUploadException;17 importorg.apache.commons.fileupload.servlet.ServletFileUpload;18 importorg.apache.commons.fileupload.util.Streams;19

20 public classHTTPPostAcceptPhoto {21

22 Map result = new HashMap();23

24 public Mapanalyze(HttpServletRequest request,25 HttpServletResponse response,String imageurl) {26 if (ServletFileUpload.isMultipartContent(request)) {//判断是否含有文件

27 insertPIC(request,imageurl);28 } else{29 txthandle(request, response);30 }31 returnresult;32 }33 //写出图片

34 private voidinsertPIC(HttpServletRequest request,String url) {35

36 ServletFileUpload upload = newServletFileUpload();37 FileItemIterator iter;38 try{39 iter =upload.getItemIterator(request);40 while(iter.hasNext()) {41 FileItemStream item =iter.next();42 String name = item.getFieldName();//filename

43 InputStream stream =item.openStream();44 System.out.println("文本" +item.isFormField());45 if (item.isFormField()) {//如果是文本

46 txt(result,name, Streams.asString(stream,"utf-8"));47 } else{48 String dir =request.getSession().getServletContext()49 .getRealPath(url);50 OutputStream fileos = null;51 byte[] buff = new byte[1];52 File image =newFile(dir, item.getName());53 System.out.println(" item.getName():"+item.getName());54 fileos = new BufferedOutputStream(newFileOutputStream(55 image));56

57 while ((stream.read(buff)) != -1) {58 fileos.write(buff);59 }60 fileos.flush();61 fileos.close();62 result.put("imagename", item.getName());//返回图片名字

63 }64 }65 } catch(FileUploadException e) {66 //TODO Auto-generated catch block

67 System.out.println(e);68 } catch(IOException e) {69 //TODO Auto-generated catch block

70 System.out.println(e);71 }72 }73 //有文本时的操作

74 private void txt(Mapresult,String name, String asString){75 result.put(name, asString);76 }77 //纯文本操作

78 public voidtxthandle(HttpServletRequest request,79 HttpServletResponse response){80 result =request.getParameterMap();81 }82

83 }

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值