android 上传图片到服务器Tomcat(Struts2)

时间:2021-11-07 12:16:05

在做android开发的时候,有时你会用到图片的上传功能,在我的android项目中,我是选中图片,点击上传多张图片

android客户端上传图片部分的代码如下:

package com.example.myphotos.utils;
 
import java.io.DataOutputStream;
import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;
import java.io.InputStream;
import java.net.HttpURLConnection;
import java.net.MalformedURLException;
import java.net.URL;
import java.util.UUID;
 
import android.util.Log;
 
public class UploadUtil {
    private static final String TAG = "uploadFile";
    private static final int TIME_OUT = 10 * 1000; // 超时时间
    private static final String CHARSET = "utf-8"; // 设置编码
 
    /**
     * 上传文件到服务器
     * 
     * @param file
     *            需要上传的文件
     * @param RequestURL
     *            请求的rul
     * @return 返回响应的内容
     */
    public static int uploadFile(File file, String RequestURL) {
        int res = 0;
        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.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);
 
            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是文件的名字,包含后缀名
                 */
 
                sb.append("Content-Disposition: form-data; name=\"file\"; 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=成功 当响应成功,获取响应的流
                 */
                res = conn.getResponseCode();
                Log.e(TAG, "response code:" + res);
                if (res == 200) {
                    Log.e(TAG, "request success");
                    InputStream input = conn.getInputStream();
                    StringBuffer sb1 = new StringBuffer();
                    int ss;
                    while ((ss = input.read()) != -1) {
                        sb1.append((char) ss);
                    }
                    result = sb1.toString();
                    Log.e(TAG, "result : " + result);
                } else {
                    Log.e(TAG, "request error");
                }
            }
        } catch (MalformedURLException e) {
            e.printStackTrace();
        } catch (IOException e) {
            e.printStackTrace();
        }
        return res;
    }
}

服务器段的代码如下:

服务器端用的Struts2

package www.csdn.image;
 
import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;
import java.util.Random;
 
import javax.servlet.ServletInputStream;
import javax.servlet.http.HttpServletRequest;
 
import org.apache.commons.fileupload.DiskFileUpload;
import org.apache.struts2.ServletActionContext;
 
import com.opensymphony.xwork2.Action;
import com.opensymphony.xwork2.ActionContext;
import com.opensymphony.xwork2.ActionSupport;
 
/**
 * ImagesAction 2013-6-18 下午9:02:58
 *
 * @author 乔晓松
 *
 */
public class ImagesAction extends ActionSupport {
 
 /**
  *
  */
 private static final long serialVersionUID = 1L;
 
 public List<String> list = new ArrayList<String>();
 private File file;
 private String fileContentType;
 private String fileFileName;
 
 public File getFile() {
  return file;
 }
 
 public void setFile(File file) {
  this.file = file;
 }
 
 public String getFileContentType() {
  return fileContentType;
 }
 
 public void setFileContentType(String fileContentType) {
  this.fileContentType = fileContentType;
 }
 
 public String getFileFileName() {
  return fileFileName;
 }
 
 public void setFileFileName(String fileFileName) {
  this.fileFileName = fileFileName;
 }
 
 public List<String> getList() {
  return list;
 }
 
 public String httpAllImages() {
  String path = ServletActionContext.getServletContext().getRealPath(
    "images");
  // System.out.println(path);
  File filePath = new File(path);
  File[] files = filePath.listFiles();
  for (int i = 0; i < files.length; i++) {
   File file = files[i];
   if (!file.isDirectory()) {
    String fileName = file.getName();
    String img = fileName.substring(fileName.lastIndexOf(".") + 1);
    if ("jpg".equals(img) || "jpeg".equals(img)
      || "gif".equals(img) || "png".equals(img)) {
 
     list.add(fileName);
    }
   }
  }
  System.out.println(list.size());
  return "images";
 }
 
 @SuppressWarnings("deprecation")
 public String uploadFile() {
  System.out.println("-----------------");
  System.out.println(fileFileName + "------------------" + file.length());
  try {
   FileInputStream fis = new FileInputStream(file);
   String photospath = ServletActionContext.getRequest().getRealPath(
     "photos");
   System.out.println(photospath);
   File fs = new File(photospath, fileFileName);
   FileOutputStream fos = new FileOutputStream(fs);
   int len = 0;
   byte[] buffer = new byte[1024];
 
   while ((len = fis.read(buffer)) != -1) {
    fos.write(buffer, 0, len);
   }
   fos.flush();
   fos.close();
   fis.close();
 
  } catch (FileNotFoundException e) {
   e.printStackTrace();
  } catch (IOException e) {
   e.printStackTrace();
  }
 
  return "uploadfile";
 }
<?xml version="1.0" encoding="UTF-8" ?>
<!DOCTYPE struts PUBLIC
    "-//Apache Software Foundation//DTD Struts Configuration 2.3//EN"
    "http://struts.apache.org/dtds/struts-2.3.dtd">
<struts>
    <include file="struts-constant.xml"></include>
    <package name="test" namespace="/csdn" extends="json-default">
        <action name="ImagesAction_*" class="www.csdn.image.ImagesAction"
            method="{1}">
            <result name="images" type="json">list</result>
            <result name="uploadfile"></result>
        </action>
    </package>
</struts>

 图片上传:http://topmanopensource.iteye.com/blog/1605238(有例子)。

      http://blog.csdn.net/lmj623565791/article/details/23781773