使用Java代码如何上传文件到Stuts Action中??

使用Java代码如何上传文件到Stuts Action中??
求大神。。。。。

5个回答

刚好写过直接上代码了

调用的地方的代码
[code="java"]
URL url = new URL(imageHttp);
BufferedImage img = ImageIO.read(url);
File file = new File(System.currentTimeMillis()+".jpg");
ImageIO.write(img, "jpg", file);
FileBody pic = new FileBody(file);

                            MultipartEntity reqEntity = new MultipartEntity();
                            StringBody content1 = new StringBody(content,Charset.forName("UTF-8"));
                            StringBody access_token = new StringBody(qq_access_token,Charset.forName("UTF-8"));
                            StringBody oauth_consumer_key = new StringBody(QQConnectConfig.getValue("app_ID").trim(),Charset.forName("UTF-8"));
                            StringBody openid = new StringBody(qq_open_id,Charset.forName("UTF-8"));
                            reqEntity.addPart("pic", pic);
                            reqEntity.addPart("access_token", access_token);
                            reqEntity.addPart("oauth_consumer_key", oauth_consumer_key);
                            reqEntity.addPart("openid", openid);
                            reqEntity.addPart("content", content1);

                            String res = HttpClientUtil.executeMultipartPOST(QQConnectConfig.getValue("addPicTURL"),reqEntity);
                            System.out.println("================="+res);
                            img.flush();
                            img=null;

[/code]

工具类代码
[code="java"]
/**

  • Project Name:live_app
  • Package Name:com.kuke.core.engine
  • File Name:HttpClientUtil.java
  • Create Time:2012-4-5 下午04:49:55
  • Copyright (c) 2006 ~ 2012 Kuke Tech Dept All rights reserved. */ package com.kuke.core.util;

import java.io.IOException;
import java.util.List;

import org.apache.http.client.HttpClient;
import org.apache.http.client.ResponseHandler;
import org.apache.http.client.entity.UrlEncodedFormEntity;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.entity.mime.MultipartEntity;
import org.apache.http.impl.client.BasicResponseHandler;
import org.apache.http.impl.client.DefaultHttpClient;
import org.apache.http.params.HttpConnectionParams;
import org.apache.http.protocol.HTTP;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

/**
*Class HttpClientUtil
*Descripton goes here
*@author:zhjt
*@version: Revision:2.0.0, 2012-4-5 下午04:49:55
*/
public final class HttpClientUtil
{
static Logger logger = LoggerFactory.getLogger(HttpClientUtil.class);

static int CONNECTIONTIMEOUTMILLIS = 10000;

static int SOCKETTIMEOUTMILLIS = 10000;


/**
 * 执行Http的返回结果<Get>
 */
public static String executeService(String url)throws Exception {
    logger.debug("SSOService executeService start!");
    logger.debug("url=" + url);
    String result = "";
    DefaultHttpClient httpclient = new DefaultHttpClient();

    //设置超时事件
    HttpConnectionParams.setConnectionTimeout(httpclient.getParams(),CONNECTIONTIMEOUTMILLIS);   
    HttpConnectionParams.setSoTimeout(httpclient.getParams(), SOCKETTIMEOUTMILLIS);          

    try {
        HttpGet httpget = new HttpGet(url);
        ResponseHandler<String> responseHandler = new BasicResponseHandler();
        String responseBody = httpclient.execute(httpget, responseHandler);
        result=responseBody;                
        logger.debug("SSOService executeService end!");
    }catch(Exception e){
        logger.debug("SSOService executeService error:"+e);         
    } finally {
        httpclient.getConnectionManager().shutdown();
        logger.debug("SSOService executeService shutdown!");
    }
    return result;
}

/**
 * 执行Http的返回结果<POST>
 */
public static String executeServicePOST(String url, List nvps)
        throws IOException {
    logger.debug("SSOService executeServicePOST start!");   
    String result = "";
    DefaultHttpClient httpclient = new DefaultHttpClient();

    //设置超时事件
    HttpConnectionParams.setConnectionTimeout(httpclient.getParams(), CONNECTIONTIMEOUTMILLIS);   
    HttpConnectionParams.setSoTimeout(httpclient.getParams(), SOCKETTIMEOUTMILLIS);          
    try {
        HttpPost httpost = new HttpPost( url + "?");
        httpost.setEntity(new UrlEncodedFormEntity(nvps, HTTP.UTF_8));
        ResponseHandler<String> responseHandler = new BasicResponseHandler();
        String responseBody = httpclient.execute(httpost, responseHandler);
        result=responseBody;
        logger.debug("SSOService executeServicePOST end!");
    }catch(Exception e){
        logger.debug("SSOService executeServicePOST error:"+e);         
    } finally {
        httpclient.getConnectionManager().shutdown();
        logger.debug("SSOService executeServicePOST shutdown!");
    }
    return result;
}

public static String executeMultipartPOST(String url, MultipartEntity reqEntity) {
    logger.debug(" executeMultipartPOST start!");
    String result = "";
    HttpClient httpclient = new DefaultHttpClient();
    try {
        HttpPost httppost = new HttpPost(url);
        httppost.setEntity(reqEntity);
        httppost.getRequestLine();
        ResponseHandler<String> responseHandler = new BasicResponseHandler();
        String responseBody = httpclient.execute(httppost, responseHandler);

// HttpResponse response = httpclient.execute(httppost);
// HttpEntity resEntity = response.getEntity();
result=responseBody;
}catch(Exception e){
logger.debug("executeMultipartPOST error:"+e);
} finally {
httpclient.getConnectionManager().shutdown();
}
return result;
}
}

[/code]

lorewolf311
tianchao_ executeMultipartPOST 这个方法是上传文件的
大约 6 年之前 回复
enrive
一于 你可能没有理解我的意思,不是使用浏览器,而是使用Java代码发送请求。。。
大约 6 年之前 回复

HttpURLConnection
文件内容读取出来 然后发送过去

enrive
一于 本想在struts action中获取请求的输入流,然后根据其格式在发过去,但不知在在action中如何获取请求输入流,求回答。。。。
大约 6 年之前 回复

这个技术其实很简单的,这个有个好网站 你一看就知道了 www.126.am/MmlIv3

相当于用java 代码来模拟浏览器的动作。那哥们连代码都贴全了。。。

Csdn user default icon
上传中...
上传图片
插入图片
抄袭、复制答案,以达到刷声望分或其他目的的行为,在CSDN问答是严格禁止的,一经发现立刻封号。是时候展现真正的技术了!
立即提问