我有个图片上传服务器的demo 但用的是HttpConnection来做的

解决方案 »

  1.   

    后台用的是struct2框架来接受图片的上传
      

  2.   

    客户端代码/**
     * 上传文件到服务器
     * @param file
     * @return
     * @throws Exception
     */
    public Json uploadLocal(File file) throws Exception {
    fileSize = (int) file.length();
    if (null != progress) {progress.setMax(fileSize);}
    String url = "http://192.168.1.58:8088/test/other/httpTakeFile.htm";
    HttpURLConnection conn = (HttpURLConnection) new URL(url).openConnection();
    conn.setDoOutput(true);conn.setDoInput(true);
    conn.setChunkedStreamingMode(1024 * 1024);
    conn.setRequestMethod(Domain.REQUEST_POST);
    conn.setRequestProperty("connection", "Keep-Alive");
    conn.setRequestProperty("Charsert", HTTP.UTF_8);
    conn.setRequestProperty("Content-Type", "multipart/form-data;file=" + file.getName());
    conn.setRequestProperty("ext", file.getName().substring(file.getName().lastIndexOf(".")));
    OutputStream output = conn.getOutputStream();InputStream input = new FileInputStream(file);
    int i = 0, total = 0;
    byte[] buffer = new byte[1024];
    while ((i = input.read(buffer)) != -1) {
    output.write(buffer, 0, i);
    total += i;
    if (null != progress) {progress.setProgress(total);}
    }
    String response = readFile(conn.getInputStream(), HTTP.UTF_8, 1, false);
    input.close();output.flush();output.close();conn.disconnect();
    JSONObject object = new JSONObject(response);
    Json vo = new Json(object.getBoolean("success"), object.getString("message"));
    JSONObject data = null;try {data = (JSONObject) object.get("data");} catch (Exception e) {}
    if (null != data) {
    Iterator iterator = data.keys();
    while (iterator.hasNext()) {
    String key = (String) iterator.next();vo.getData().put(key, data.get(key));
    }
    }
    return vo;
    }服务器端代码:
    /**
     * http上传文件
     * @return
     */
    public Json httpTakeFile() {
    try {
    CommUtil.checkRequestMethod(Constant.REQUEST_POST);
    String folder = FileUtil.UPLOAD_TEMP_PATH + "10/";
    return new Json(true, Json.OPERATE_RIGHT_MESSAGE).
    addData("fileUrl", FileUtil.readRootUrl() + folder + FileUtil.httpTakeFile(FileUtil.getBasePath() + folder));
    } catch (Exception e) {
    log.error("http上传文件", e);
    return new Json(false, e.getMessage());
    }
    }