Activity 获取时没有问题,都能打印出picPath
上传都可以打印出file的path和name
public class UploadUtil {
private static final String TAG = "uploadFile";
private static final int TIME_OUT = 10 * 1000; // 锟斤拷时时锟斤拷
private static final String CHARSET = "utf-8"; // 锟斤拷锟矫憋拷锟斤拷
private int readTimeOut = 10 * 1000; // 读取超时
private int connectTimeout = 10 * 1000; // 超时时间
private static final String BOUNDARY = UUID.randomUUID().toString(); // 边界标识
// 随机生成
private static final String PREFIX = "--";
private static final String LINE_END = "\r\n";
private static final String CONTENT_TYPE = "multipart/form-data"; // 内容类型 public int uploadFile(File file, String RequestURL, int id, String table) {
int res = 0;
Log.e("file", file.getName()+ " " + file.getPath());
long requestTime = System.currentTimeMillis();
long responseTime = 0;
String result = "";
String getUrl = RequestURL + "/Upload.action";
try {
URL url = new URL(getUrl);
HttpURLConnection conn = (HttpURLConnection) url.openConnection();
conn.setReadTimeout(readTimeOut);
conn.setConnectTimeout(connectTimeout);
conn.setDoInput(true); // 允许输入流
conn.setDoOutput(true); // 允许输出流
conn.setUseCaches(false); // 不允许使用缓存
conn.setRequestMethod("POST"); // 请求方式
conn.setRequestProperty("Charset", CHARSET); // 设置编码
conn.setRequestProperty("connection", "keep-alive");
conn.setRequestProperty("user-agent",
"Mozilla/4.0 (compatible; MSIE 6.0; Windows NT 5.1; SV1)");
conn.setRequestProperty("Content-Type", CONTENT_TYPE + ";boundary="
+ BOUNDARY);
DataOutputStream dos = new DataOutputStream(conn.getOutputStream());
StringBuffer sb = null;
String params = ""; sb = null;
params = null;
sb = new StringBuffer();
sb.append(PREFIX).append(BOUNDARY).append(LINE_END);
sb.append("Content-Disposition:form-data; name=\"" + "pic"
+ "\"; filename=\"" + file.getName() + "\"" + LINE_END);
sb.append("Content-Type:image/pjpeg" + LINE_END);
sb.append(LINE_END);
params = sb.toString();
sb = null; Log.i(TAG, file.getName() + "=" + params + "##");
dos.write(params.getBytes());
InputStream is = new FileInputStream(file);
byte[] bytes = new byte[1024];
int len = 0;
int curLen = 0;
while ((len = is.read(bytes)) != -1) {
curLen += len;
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();
res = conn.getResponseCode();
responseTime = System.currentTimeMillis();
requestTime = (int) ((responseTime - requestTime) / 1000);
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);
res = uploadTable(result, id, table, RequestURL); } else {
Log.e(TAG, "request error"); }
} catch (MalformedURLException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
return res;
} public int doUpload(File file, String RequestURL, int id, String table) {
int res = 0;
String getUrl = RequestURL + "/Upload.action";
String end = "\r\n";
String twoHyphens = "--";
String boundary = "*****";
Log.e("file", file.getName()+ " " + file.getPath());
try {
URL url = new URL(getUrl);
HttpURLConnection con = (HttpURLConnection) url.openConnection();
con.setDoInput(true);
con.setDoOutput(true);
con.setUseCaches(false);
con.setRequestMethod("POST");
con.setRequestProperty("Connection", "Keep-Alive");
con.setRequestProperty("Charset", "UTF-8");
con.setRequestProperty("Content-Type",
"multipart/form-data;boundary=" + boundary);
DataOutputStream ds = new DataOutputStream(con.getOutputStream());
ds.writeBytes(twoHyphens + boundary + end);
ds.writeBytes("Content-Disposition: form-data; "
+ "name=\"file1\";filename=\"" + file.getName() + "\"" + end);
ds.writeBytes(end);
FileInputStream fStream = new FileInputStream(file);
int bufferSize = 1024;
byte[] buffer = new byte[bufferSize];
int length = -1;
while ((length = fStream.read(buffer)) != -1) {
ds.write(buffer, 0, length);
}
ds.writeBytes(end);
ds.writeBytes(twoHyphens + boundary + twoHyphens + end);
fStream.close();
ds.flush();
InputStream is = con.getInputStream();
int ch;
StringBuffer b = new StringBuffer();
while ((ch = is.read()) != -1) {
b.append((char) ch);
}
String result = b.toString();
Log.e("result", result);
ds.close();
res = uploadTable(result, id, table, RequestURL);
} catch (Exception e) {
e.printStackTrace();
} return res;
} public int uploadTable(String result, int id, String table, String url) {
int res = 0;
String getUrl = url + "/InsertTabel.action?id=" + id + "&table="
+ table + "&url=" + result;
HttpClient httpclient = new DefaultHttpClient();
try {
HttpPost post = new HttpPost(new URI(getUrl));
HttpResponse response = httpclient.execute(post);
if (response.getStatusLine().getStatusCode() == 200
&& response != null) {
HttpEntity entity = response.getEntity();
String json = EntityUtils.toString(entity);
JSONObject obj = new JSONObject(json);
res = obj.getInt("result");
}
} catch (Exception e) {
e.printStackTrace();
}
return res;
}
}
后台读取public String upload() throws Exception
{
System.out.println("上传");
PrintWriter pw = response.getWriter();
int index = 0;
try
{
DiskFileUpload fu = new DiskFileUpload();
List fileItems = null;
try
{
fileItems = fu.parseRequest(request);
System.out.println("fileItems=" + fileItems);
Iterator iter = fileItems.iterator(); // 依次处理每个上传的文件
while (iter.hasNext())
{
FileItem item = (FileItem) iter.next();// 忽略其他不是文件域的所有表单信息
if (!item.isFormField())
{
String name = item.getName();// 获取上传文件名,包括路径
name = name.substring(name.lastIndexOf("\\") + 1);// 从全路径中提取文件名
long size = item.getSize();
if ((name == null || name.equals("")) && size == 0) continue;
int point = name.indexOf(".");
name = (new Date()).getTime() + name.substring(point, name.length()) + index;
index++;
File fNew = new File(getSavePath(), name);
try
{
item.write(fNew);
}
catch (Exception e)
{
e.printStackTrace(); }
pw.write(getSavePath()+ "//"+ name);
}
else
{
String fieldvalue = item.getString(); // 如果包含中文应写为:(转为UTF-8编码)
// String fieldvalue = new String(item.getString().getBytes(),"UTF-8");
}
} }
catch (Exception e)
{
e.printStackTrace();
}
}
catch (Exception e)
{
}
return SUCCESS;
}
后台打印fileItems=[],获取不到file文件。
上传都可以打印出file的path和name
public class UploadUtil {
private static final String TAG = "uploadFile";
private static final int TIME_OUT = 10 * 1000; // 锟斤拷时时锟斤拷
private static final String CHARSET = "utf-8"; // 锟斤拷锟矫憋拷锟斤拷
private int readTimeOut = 10 * 1000; // 读取超时
private int connectTimeout = 10 * 1000; // 超时时间
private static final String BOUNDARY = UUID.randomUUID().toString(); // 边界标识
// 随机生成
private static final String PREFIX = "--";
private static final String LINE_END = "\r\n";
private static final String CONTENT_TYPE = "multipart/form-data"; // 内容类型 public int uploadFile(File file, String RequestURL, int id, String table) {
int res = 0;
Log.e("file", file.getName()+ " " + file.getPath());
long requestTime = System.currentTimeMillis();
long responseTime = 0;
String result = "";
String getUrl = RequestURL + "/Upload.action";
try {
URL url = new URL(getUrl);
HttpURLConnection conn = (HttpURLConnection) url.openConnection();
conn.setReadTimeout(readTimeOut);
conn.setConnectTimeout(connectTimeout);
conn.setDoInput(true); // 允许输入流
conn.setDoOutput(true); // 允许输出流
conn.setUseCaches(false); // 不允许使用缓存
conn.setRequestMethod("POST"); // 请求方式
conn.setRequestProperty("Charset", CHARSET); // 设置编码
conn.setRequestProperty("connection", "keep-alive");
conn.setRequestProperty("user-agent",
"Mozilla/4.0 (compatible; MSIE 6.0; Windows NT 5.1; SV1)");
conn.setRequestProperty("Content-Type", CONTENT_TYPE + ";boundary="
+ BOUNDARY);
DataOutputStream dos = new DataOutputStream(conn.getOutputStream());
StringBuffer sb = null;
String params = ""; sb = null;
params = null;
sb = new StringBuffer();
sb.append(PREFIX).append(BOUNDARY).append(LINE_END);
sb.append("Content-Disposition:form-data; name=\"" + "pic"
+ "\"; filename=\"" + file.getName() + "\"" + LINE_END);
sb.append("Content-Type:image/pjpeg" + LINE_END);
sb.append(LINE_END);
params = sb.toString();
sb = null; Log.i(TAG, file.getName() + "=" + params + "##");
dos.write(params.getBytes());
InputStream is = new FileInputStream(file);
byte[] bytes = new byte[1024];
int len = 0;
int curLen = 0;
while ((len = is.read(bytes)) != -1) {
curLen += len;
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();
res = conn.getResponseCode();
responseTime = System.currentTimeMillis();
requestTime = (int) ((responseTime - requestTime) / 1000);
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);
res = uploadTable(result, id, table, RequestURL); } else {
Log.e(TAG, "request error"); }
} catch (MalformedURLException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
return res;
} public int doUpload(File file, String RequestURL, int id, String table) {
int res = 0;
String getUrl = RequestURL + "/Upload.action";
String end = "\r\n";
String twoHyphens = "--";
String boundary = "*****";
Log.e("file", file.getName()+ " " + file.getPath());
try {
URL url = new URL(getUrl);
HttpURLConnection con = (HttpURLConnection) url.openConnection();
con.setDoInput(true);
con.setDoOutput(true);
con.setUseCaches(false);
con.setRequestMethod("POST");
con.setRequestProperty("Connection", "Keep-Alive");
con.setRequestProperty("Charset", "UTF-8");
con.setRequestProperty("Content-Type",
"multipart/form-data;boundary=" + boundary);
DataOutputStream ds = new DataOutputStream(con.getOutputStream());
ds.writeBytes(twoHyphens + boundary + end);
ds.writeBytes("Content-Disposition: form-data; "
+ "name=\"file1\";filename=\"" + file.getName() + "\"" + end);
ds.writeBytes(end);
FileInputStream fStream = new FileInputStream(file);
int bufferSize = 1024;
byte[] buffer = new byte[bufferSize];
int length = -1;
while ((length = fStream.read(buffer)) != -1) {
ds.write(buffer, 0, length);
}
ds.writeBytes(end);
ds.writeBytes(twoHyphens + boundary + twoHyphens + end);
fStream.close();
ds.flush();
InputStream is = con.getInputStream();
int ch;
StringBuffer b = new StringBuffer();
while ((ch = is.read()) != -1) {
b.append((char) ch);
}
String result = b.toString();
Log.e("result", result);
ds.close();
res = uploadTable(result, id, table, RequestURL);
} catch (Exception e) {
e.printStackTrace();
} return res;
} public int uploadTable(String result, int id, String table, String url) {
int res = 0;
String getUrl = url + "/InsertTabel.action?id=" + id + "&table="
+ table + "&url=" + result;
HttpClient httpclient = new DefaultHttpClient();
try {
HttpPost post = new HttpPost(new URI(getUrl));
HttpResponse response = httpclient.execute(post);
if (response.getStatusLine().getStatusCode() == 200
&& response != null) {
HttpEntity entity = response.getEntity();
String json = EntityUtils.toString(entity);
JSONObject obj = new JSONObject(json);
res = obj.getInt("result");
}
} catch (Exception e) {
e.printStackTrace();
}
return res;
}
}
后台读取public String upload() throws Exception
{
System.out.println("上传");
PrintWriter pw = response.getWriter();
int index = 0;
try
{
DiskFileUpload fu = new DiskFileUpload();
List fileItems = null;
try
{
fileItems = fu.parseRequest(request);
System.out.println("fileItems=" + fileItems);
Iterator iter = fileItems.iterator(); // 依次处理每个上传的文件
while (iter.hasNext())
{
FileItem item = (FileItem) iter.next();// 忽略其他不是文件域的所有表单信息
if (!item.isFormField())
{
String name = item.getName();// 获取上传文件名,包括路径
name = name.substring(name.lastIndexOf("\\") + 1);// 从全路径中提取文件名
long size = item.getSize();
if ((name == null || name.equals("")) && size == 0) continue;
int point = name.indexOf(".");
name = (new Date()).getTime() + name.substring(point, name.length()) + index;
index++;
File fNew = new File(getSavePath(), name);
try
{
item.write(fNew);
}
catch (Exception e)
{
e.printStackTrace(); }
pw.write(getSavePath()+ "//"+ name);
}
else
{
String fieldvalue = item.getString(); // 如果包含中文应写为:(转为UTF-8编码)
// String fieldvalue = new String(item.getString().getBytes(),"UTF-8");
}
} }
catch (Exception e)
{
e.printStackTrace();
}
}
catch (Exception e)
{
}
return SUCCESS;
}
后台打印fileItems=[],获取不到file文件。
解决方案 »
- sqlite多次删除记录的问题?
- android源代码在windows下的下载
- android焦点控制问题
- 求助 看看这样的效果android有没有现成的组件来实现。
- 谁能告诉我下像懒人笨笨那样的软件的设计思路及涉及技术
- android logcat 权限过滤
- 系統莫名其妙 crash
- 开发一个android富文本编辑器
- android.content.pm.PackageManager$NameNotFoundException,请问各位好心大神这个一般是什么错误 怎么解决
- cordova inappbrowser 浏览器 中怎样导出excel
- Android MediaRecorder 录音setAudioSource failed
- 如何让进度条对话框先出现。。。小白求教
String regString = null;
HttpPost httpRequest =new HttpPost(urlAdds);
try {
//发出HTTP request
System.out.println("图片路径==="+imagePath);
//httpRequest.setEntity(new UrlEncodedFormEntity(params,HTTP.UTF_8));
MultipartEntity entity = new MultipartEntity();
for (Map.Entry<String, String> entry : params.entrySet()) {
entity.addPart(entry.getKey(), new StringBody(entry.getValue()));
}
if(null != imagePath) {
System.out.println("图片路径1==="+imagePath);
File file = new File(imagePath);
entity.addPart("authenfile", new FileBody(file));
}
httpRequest.setEntity(entity);
//取得HTTP response
HttpResponse httpResponse = new DefaultHttpClient().execute(httpRequest);
//若状态码为200 ok
System.out.println("状态吗====="+httpResponse.getStatusLine().getStatusCode());
if(httpResponse.getStatusLine().getStatusCode() == 200){
isNetError = false;
//注册返回值
regString = EntityUtils.toString(httpResponse.getEntity());
}else {
Log.e("serviceError", "the service is error!");
}
}catch(ClientProtocolException e) {
isNetError = true;
return regString;
}catch(UnsupportedEncodingException e) {
isNetError = true;
return regString;
}catch(IOException e) {
isNetError = true;
return regString;
} return regString;
}
无关版本问题,你去下载个apache-mime4j-0.6.jar导进去就可以了