Android 上传图片实例,java上传图片接口
1、完整上傳圖片代碼方法:
private static final int TIME_OUT = 10*1000; //超時時間 private static final String CHARSET = "utf-8"; //設(shè)置編碼 /*** android上傳文件到服務(wù)器* @param file 需要上傳的文件* @param RequestURL 請求的rul* @return 返回響應(yīng)的內(nèi)容*/public static String uploadFile(File file, String RequestURL){String result = null;String BOUNDARY = UUID.randomUUID().toString(); //邊界標(biāo)識 隨機生成String PREFIX = "--" , LINE_END = "\r\n";String CONTENT_TYPE = "multipart/form-data"; //內(nèi)容類型try {URL url = new URL(RequestURL);HttpURLConnection conn = (HttpURLConnection) url.openConnection();conn.setRequestProperty("filename",file.getName());//添加頭部參數(shù),只有這個key 才可以得到對應(yīng)的文件conn.setReadTimeout(TIME_OUT);conn.setConnectTimeout(TIME_OUT);conn.setDoInput(true); //允許輸入流conn.setDoOutput(true); //允許輸出流conn.setUseCaches(false); //不允許使用緩存conn.setRequestMethod("POST"); //請求方式conn.setRequestProperty("Charset", CHARSET); //設(shè)置編碼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){/*** 當(dāng)文件不為空,把文件包裝并且上傳*/DataOutputStream dos = new DataOutputStream( conn.getOutputStream());StringBuffer sb = new StringBuffer(); // sb.append(PREFIX); // sb.append(BOUNDARY); // sb.append(LINE_END);/*** 這里重點注意:* name里面的值為服務(wù)器端需要key 只有這個key 才可以得到對應(yīng)的文件* 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();/*** 獲取響應(yīng)碼 200=成功* 當(dāng)響應(yīng)成功,獲取響應(yīng)的流*/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;}@Overrideprotected String doInBackground(String... strings) {return uploadFile(file,strings[0]);}@Overrideprotected 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、手機上傳圖片到j(luò)ava后臺效果
手機選擇圖片
?java創(chuàng)建文件方法
?上傳成功!!
?
demo鏈接:https://download.csdn.net/download/meixi_android/10976495
https://download.csdn.net/download/meixi_android/11006216
?
在線回復(fù)bug:QQ1085220040
?
附j(luò)ava??HttpServlet 上傳圖片主要方法完整代碼實例:
?? ?public void lgqservice(HttpServletRequest request,
?? ??? ??? ?HttpServletResponse response) throws ServletException, IOException {
?? ??? ?String filename = request.getHeader("filename");
?? ??? ?System.out.println("===service進(jìn)來了====="+ 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));
?? ?}
總結(jié)
以上是生活随笔為你收集整理的Android 上传图片实例,java上传图片接口的全部內(nèi)容,希望文章能夠幫你解決所遇到的問題。
- 上一篇: Node.js中使用AWS SNS服务发
- 下一篇: SP和Fuction的关系