码迷,mamicode.com
首页 > 移动开发 > 详细

android 文件上传

时间:2015-09-30 18:05:20      阅读:210      评论:0      收藏:0      [点我收藏+]

标签:

1.服务端

1.1 相关jar包

        <dependency>
            <groupId>commons-fileupload</groupId>
            <artifactId>commons-fileupload</artifactId>
            <version>1.3.1</version>
        </dependency>

1.2代码

public class Upload extends HttpServlet {
    private static final long serialVersionUID = 1L;

    @Override
    protected void service(HttpServletRequest req, HttpServletResponse resp)
            throws ServletException, IOException {
        try {
            String fileDir="e:/fileUpload/";
            DiskFileItemFactory dfif=new DiskFileItemFactory(4, new File("e:/tempPath"));
            ServletFileUpload sfu=new ServletFileUpload(dfif);
            List<FileItem> files= sfu.parseRequest(req);
            
            if(files!=null){
                for (FileItem fileItem : files) {
                    String fileName= fileItem.getName();
                    fileItem.write(new File(fileDir+fileName));
                }
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
    }
}

2.客户端

            HttpPost httpPost = new HttpPost(actionUrl);
            MultipartEntity reqEntity = new MultipartEntity(HttpMultipartMode.BROWSER_COMPATIBLE,null,Charset.forName(HTTP.UTF_8));
    
            FileBody file1 = new FileBody(myPhoto,"image", "UTF-8");
            reqEntity.addPart("file1", file1);
            httpPost.setEntity(reqEntity);
                HttpClient httpclient =new DefaultHttpClient();
                httpclient.getParams().setParameter(CoreProtocolPNames.PROTOCOL_VERSION, HttpVersion.HTTP_1_1);
//                httpclient.getParams().setParameter(CoreProtocolPNames.HTTP_CONTENT_CHARSET, Charset.forName("UTF-8"));
                httpResponse = httpclient.execute(httpPost);

 

android 文件上传

标签:

原文地址:http://www.cnblogs.com/mmdsnb/p/4849745.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!