Android 上传图片实例,java上传图片接口

1、完整上传图片代码方法:

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.setRequestProperty("filename",file.getName());//添加头部参数,只有这个key 才可以得到对应的文件
            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);
            conn.setRequestProperty("action", "upload");
            conn.connect();
            Log.e("lgq", "re==uploadFile=====" + file.getPath()+"......."+file.getName());
            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=\"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 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();
                if(res==200){
                    InputStream input =  conn.getInputStream();
//                    StringBuffer sb1= new StringBuffer();
                    int ss ;
                    byte[] buffer = new byte[1024];
                    StringBuilder builder =new StringBuilder();
                    while((ss=input.read(buffer))!=-1){
//                        sb1.append((char)ss);
                        builder.append(new String(buffer, 0, ss, "UTF-8"));
                    }
                    result = builder.toString();
                    System.out.println(result);
                }
            }
        } catch (MalformedURLException e) {
            e.printStackTrace();
        } catch (IOException e) {
            e.printStackTrace();
        }
        return result;
    }

2、异步请求方法

public class Upload extends AsyncTask<String,Void,String> {
    File file;
    public Upload(File file){
        this.file = file;
    }
    @Override
    protected String doInBackground(String... strings) {
        return uploadFile(file,strings[0]);
    }

    @Override
    protected void onPostExecute(String s) {
        super.onPostExecute(s);

        Log.i("lgq", "re==onPostExecute=====" + s);
        if(s.contains("succedd")){
            Toast.makeText(getBaseContext(),"上传成功",Toast.LENGTH_SHORT).show();
        }else{
            Toast.makeText(getBaseContext(),"上传失败",Toast.LENGTH_SHORT).show();
        }
    }
}

3、选中图片,开始上传图片

String firestrUrl = "http://192.168.0.110:8080/servletDemo/testa?method=lgqservice";
private File compressedImage1File;
new  Upload(compressedImage1File).execute(firestrUrl);

4、手机上传图片到java后台效果

手机选择图片

 java创建文件方法

 上传成功!!

 

demo链接https://download.csdn.net/download/meixi_android/10976495

https://download.csdn.net/download/meixi_android/11006216

 

在线回复bug:QQ1085220040

 

附java  HttpServlet 上传图片主要方法完整代码实例:

    public void lgqservice(HttpServletRequest request,
            HttpServletResponse response) throws ServletException, IOException {
        String filename = request.getHeader("filename");
        System.out.println("===service进来了====="+ filename);

    List<String> msgList2 = new ArrayList<String>();
        if (request.getContentLength() > 0) {
            InputStream inputStream = null;
            FileOutputStream outputStream = null;
            try {
                inputStream = request.getInputStream();
                // 给新文件拼上时间毫秒,防止重名
                long now = System.currentTimeMillis();
                File file = new File("d:/", "file-" + now + ".png");
                file.createNewFile();

                outputStream = new FileOutputStream(file);

                byte temp[] = new byte[1024];
                int size = -1;
                while ((size = inputStream.read(temp)) != -1) { // 每次读取1KB,直至读完
                    outputStream.write(temp, 0, size);
                }
                msgList2.add("succedd成功" );
                okreString = "上传成功";

            } catch (IOException e) {
                msgList2.add("defeated失败" );
                okreString = "上传失败";
            } finally {
                outputStream.close();
                inputStream.close();
            }
        }
           JSONObject result = new JSONObject();  
           result.put("success", true);  
           result.put("okstatus",okreString );
           System.out.println("FileLoadServlet=====8888==="+result);
        response.getWriter().print(result);
//        response.getWriter().print(formatJsonData("msg", msgList2));
    }

  • 2
    点赞
  • 13
    收藏
    觉得还不错? 一键收藏
  • 1
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值