HTTP接受⽂件的java实现 1package TOOLS;
2
3import java.io.BufferedOutputStream;
4import java.io.File;
5import java.io.FileOutputStream;
6import java.io.IOException;
7import java.io.InputStream;
8import java.io.OutputStream;
9import java.util.HashMap;
10import java.util.Map;
11
12import javax.servlet.http.HttpServletRequest;
13import javax.servlet.http.HttpServletResponse;
14import org.apachemons.fileupload.FileItemIterator;
15import org.apachemons.fileupload.FileItemStream;
16import org.apachemons.fileupload.FileUploadException;
17import org.apachemons.fileupload.servlet.ServletFileUpload;
18import org.apachemons.fileupload.util.Streams;
19
20public class HTTPPostAcceptPhoto {
21
22 Map<String,String> result = new HashMap<String,String>();
23
24public Map<String,String> analyze(HttpServletRequest request,
25 HttpServletResponse response,String imageurl) {
26if (ServletFileUpload.isMultipartContent(request)) {// 判断是否含有⽂件
27 insertPIC(request,imageurl);
28 } else {
29 txthandle(request, response);
30 }
31return result;
32 }
33//写出图⽚
34private void insertPIC(HttpServletRequest request,String url) {
35
36 ServletFileUpload upload = new ServletFileUpload();
37 FileItemIterator iter;
38try {
39 iter = ItemIterator(request);
40while (iter.hasNext()) {
41 FileItemStream item = ();
42 String name = FieldName();// filename
43 InputStream stream = item.openStream();
44 System.out.println("⽂本" + item.isFormField());
45if (item.isFormField()) {// 如果是⽂本
46 txt(result,name, Streams.asString(stream,"utf-8"));
47 } else {
48 String dir = Session().getServletContext()
49 .getRealPath(url);
50 OutputStream fileos = null;
51byte[] buff = new byte[1];
52 File image =new File(dir, Name());
53 System.out.println(" Name():"+ Name());
54 fileos = new BufferedOutputStream(new FileOutputStream(
55 image));
56
57while ((ad(buff)) != -1) {
58 fileos.write(buff);
59 }
60 fileos.flush();
61 fileos.close();
62 result.put("imagename", Name());//返回图⽚名字
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//有⽂本时的操作
74private void txt(Map<String,String> result,String name, String asString){
75 result.put(name, asString);
76 }
77//纯⽂本操作
78public void txthandle(HttpServletRequest request,
79 HttpServletResponse response){
80 result = ParameterMap();
81 } 82
83 }
java stream
版权声明:本站内容均来自互联网,仅供演示用,请勿用于商业和其他非法用途。如果侵犯了您的权益请与我们联系QQ:729038198,我们将在24小时内删除。
发表评论