⑴ form 表单上传图片,怎样获取图片的全路径
上传一成功的一瞬间是放到系统临时目录下的,你要通过move_uploaded_file来移动到有效目录内,如果要操作临时上传目录 ,上传时通过var_mp($_FILE)能看到的。不过意义不大哈。
⑵ android从前台传图片文件到后台Servlet,报错。但是后台通过JSP直接传文件是可以传成功。
只是数据从前台传到后台的话,写个form表单,post提交,后台servlet接收就好了,也可以jsp接收数据,很多方法。
⑶ android的自带的httpClient 怎么上传文件
Android上传文件到服务端可以使用HttpConnection 上传文件,也可以使用Android封装好的HttpClient类。当仅仅上传文件可以直接使用httpconnection 上传比较方便快捷。
1、使用HttpConection上传文件。将文件转换成表单数据流。主要的思路就自己构造个http协议内容,服务端解析报文获得表单数据。代码片段:
[java] view plain
HttpURLConnection con;
try {
con = (HttpURLConnection) url.openConnection();
con.setConnectTimeout(C_TimeOut);
/* 允许Input、Output,不使用Cache */
con.setDoInput(true);
con.setDoOutput(true);
con.setUseCaches(false);
/* 设置传送的method=POST */
con.setRequestMethod("POST");
/* setRequestProperty */
con.setRequestProperty("Connection", "Keep-Alive");
con.setRequestProperty("Charset", "UTF-8");
con.setRequestProperty("Content-Type","multipart/form-data;boundary=" + boundary);
/* 设置DataOutputStream */
DataOutputStream ds = new DataOutputStream(con.getOutputStream());
FileInputStream fStream = new FileInputStream(file);
/* 设置每次写入1024bytes */
int bufferSize = 1024;
byte[] buffer = new byte[bufferSize];
int length = -1;
/* 从文件读取数据至缓冲区 */
while((length = fStream.read(buffer)) != -1)
{
/* 将资料写入DataOutputStream中 */
ds.write(buffer, 0, length);
}
fStream.close();
ds.flush();
ds.close();
可以参考
①《在 Android 上通过模拟 HTTP multipart/form-data 请求协议信息实现图片上传》 (http://bertlee.iteye.com/blog/1134576)。
②《关于android Http访问,上传,用了三个方法 》
2、使用Android HttpClient类上传参数。下面我在网上搜到得代码,忘记出处了
[java] view plain
private static boolean sendPOSTRequestHttpClient(String path,
Map<String, String> params) throws Exception {
// 封装请求参数
List<NameValuePair> pair = new ArrayList<NameValuePair>();
if (params != null && !params.isEmpty()) {
for (Map.Entry<String, String> entry : params.entrySet()) {
pair.add(new BasicNameValuePair(entry.getKey(), entry
.getValue()));
}
}
// 把请求参数变成请求体部分
UrlEncodedFormEntity uee = new UrlEncodedFormEntity(pair, "utf-8");
// 使用HttpPost对象设置发送的URL路径
HttpPost post = new HttpPost(path);
// 发送请求体
post.setEntity(uee);
// 创建一个浏览器对象,以把POST对象向服务器发送,并返回响应消息
DefaultHttpClient dhc = new DefaultHttpClient();
HttpResponse response = dhc.execute(post);
if (response.getStatusLine().getStatusCode() == 200) {
Log.i("http", "httpclient");
return true;
}
return false;
}
3、使用httpClient上传文字信息和文件信息。使用httpClient上传文件非常的方便。不过需要导入apache-mime4j-0.6.jar 和httpmime-4.0.jar两个.jar包。
[java] view plain
// 封装请求参数
MultipartEntity mpEntity = new MultipartEntity();
if (params != null && !params.isEmpty()) {
for (Map.Entry<String, String> entry : params.entrySet()) {
StringBody par = new StringBody(entry.getValue());
mpEntity.addPart(entry.getKey(), par);
}
}
// 图片
if (!imagepath.equals("")) {
FileBody file = new FileBody(new File(imagepath));
mpEntity.addPart("photo", file);
}
// 使用HttpPost对象设置发送的URL路径
HttpPost post = new HttpPost(path);
// 发送请求体
post.setEntity(mpEntity);
// 创建一个浏览器对象,以把POST对象向服务器发送,并返回响应消息
DefaultHttpClient dhc = new DefaultHttpClient();
HttpResponse response = dhc.execute(post);
FileBody类可以把文件封装到表单中,实现附件的上传。
关于httpClient上传文件可以参考链接: http://www.eoeandroid.com/forum.php?mod=viewthread&tid=76721&page=1
需要用的的ja下载地址r:http://download.csdn.net/detail/china1988s/3791514
参考:
①《在 Android 上通过模拟 HTTP multipart/form-data 请求协议信息实现图片上传》 (http://bertlee.iteye.com/blog/1134576)。
②《关于android Http访问,上传,用了三个方法 》
⑷ 用表单上传图片应怎么做啊用PHP
<?php
set_time_limit(0);
define('ROOT',dirname(__FILE__).'/');
if($_POST['submit']){
foreach ($_FILES['upfile']['tmp_name'] as $k=>$v){
!$v || (!file_exists(ROOT.'/upload/'.$_FILES['upfile']['name'][$k]) && @getimagesize($v) && @move_uploaded_file($v,ROOT.'/upload/'.$_FILES['upfile']['name'][$k]) && print ('上传'.$_FILES['upfile']['name'][$k].'成功<br /><img src="'.$site['url'].'upload/upload/'.$_FILES['upfile']['name'][$k].'" />') )|| print ('上传'.$_FILES['upfile']['name'][$k].'失败<br />');
}
}
?>
<html>
<head>
<title>上传</title>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8">
<style type="text/css">body,td{font-family:tahoma,verdana,arial;font-size:11px;line-height:15px;background-color:white;color:#666666;margin-left:20px;}
strong{font-size:12px;}
a:link{color:#0066CC;}
a:hover{color:#FF6600;}
a:visited{color:#003366;}
a:active{color:#9DCC00;}
table.itable{}
td.irows{height:20px;background:url("index.php?i=dots") repeat-x bottom}</style>
<script language="JavaScript">
function adpload() {
document.all.upload.innerHTML = '<input name="upfile[]" type="file" style="width:200;border:1 solid #9a9999; font-size:9pt; background-color:#ffffff" size="25"><br /><input name="upfile[]" type="file" style="width:200;border:1 solid #9a9999; font-size:9pt; background-color:#ffffff" size="25"><br />'+document.all.upload.innerHTML;
}
</script>
</head>
<body>
<center><form enctype="multipart/form-data" method="post" name="upform">
上传图片:按上传按纽,上传成功后可以直接粘贴图片于编辑器中 <br><br>
<a href='#' onClick="adpload()">增加上传文件</a><br><br>
<input name="upfile[]" type="file" style="width:200;border:1 solid #9a9999; font-size:9pt; background-color:#ffffff" size="25"><br>
<input name="upfile[]" type="file" style="width:200;border:1 solid #9a9999; font-size:9pt; background-color:#ffffff" size="25"><br>
<div id="upload"></div>
<input type="submit" name="submit" value="上传" style="width:30;border:1 solid #9a9999; font-size:9pt; background-color:#ffffff" size="25"><br><br><br>
<br><br>
<a href="index.php">返回</a><br />
</form>
</center>
</body>
</html>
⑸ android一次上传多张图片,我的代码如下,我希望只访问一次服务器,上传多张图片,求大神指导!
将所有图片放在一个数组中,,使用轮询,将整个数组里的内容全部上传即可,代码有点多,我就不写了,你可以在网上搜到的
⑹ android如何实现图片批量上传
首先,以下架构下的批量文件上传可能会失败或者不会成功:
1.android客户端+springMVC服务端:服务端采用org.springframework.web.multipart.MultipartHttpServletRequest作为批量上传接收类,这种搭配下的批量文件上传会失败,最终服务端只会接受到一个文件,即只会接受到第一个文件。可能因为MultipartHttpServletRequest对servlet原本的HttpServletRequest类进行封装,导致批量上传有问题。
2.android客户端+strutsMVC服务端:
上传成功的方案:
采用android客户端+Servlet(HttpServletRequest)进行文件上传。
Servlet端代码如下:
[java] view plainprint?
DiskFileItemFactory factory = new DiskFileItemFactory();
ServletFileUpload upload = new ServletFileUpload(factory);
try
{
List items = upload.parseRequest(request);
Iterator itr = items.iterator();
while (itr.hasNext())
{
FileItem item = (FileItem) itr.next();
if (item.isFormField())
{
System.out.println("表单参数名:" + item.getFieldName() + ",表单参数值:" + item.getString("UTF-8"));
}
else
{
if (item.getName() != null && !item.getName().equals(""))
{
System.out.println("上传文件的大小:" + item.getSize());
System.out.println("上传文件的类型:" + item.getContentType());
// item.getName()返回上传文件在客户端的完整路径名称
System.out.println("上传文件的名称:" + item.getName());
File tempFile = new File(item.getName());
// 上传文件的保存路径
File file = new File(sc.getRealPath("/") + savePath, tempFile.getName());
item.write(file);
request.setAttribute("upload.message", "上传文件成功!");
} else
{
request.setAttribute("upload.message", "没有选择上传文件!");
}
}
}
}
catch (FileUploadException e)
{
e.printStackTrace();
}
catch (Exception e)
{
e.printStackTrace();
request.setAttribute("upload.message", "上传文件失败!");
}
request.getRequestDispatcher("/uploadResult.jsp").forward(request, response);
android端代码如下:
[java] view plainprint?
public class SocketHttpRequester {
/**
*多文件上传
* 直接通过HTTP协议提交数据到服务器,实现如下面表单提交功能:
* <FORM METHOD=POST ACTION="http://192.168.1.101:8083/upload/servlet/UploadServlet" enctype="multipart/form-data">
<INPUT TYPE="text" NAME="name">
<INPUT TYPE="text" NAME="id">
<input type="file" name="imagefile"/>
<input type="file" name="zip"/>
</FORM>
* @param path 上传路径(注:避免使用localhost或127.0.0.1这样的路径测试,因为它会指向手机模拟器,你可以使用http://www.iteye.cn或http://192.168.1.101:8083这样的路径测试)
* @param params 请求参数 key为参数名,value为参数值
* @param file 上传文件
*/
public static boolean post(String path, Map<String, String> params, FormFile[] files) throws Exception{
final String BOUNDARY = "---------------------------7da2137580612"; //数据分隔线
final String endline = "--" + BOUNDARY + "--\r\n";//数据结束标志
int fileDataLength = 0;
for(FormFile uploadFile : files){//得到文件类型数据的总长度
StringBuilder fileExplain = new StringBuilder();
fileExplain.append("--");
fileExplain.append(BOUNDARY);
fileExplain.append("\r\n");
fileExplain.append("Content-Disposition: form-data;name=\""+ uploadFile.getParameterName()+"\";filename=\""+ uploadFile.getFilname() + "\"\r\n");
fileExplain.append("Content-Type: "+ uploadFile.getContentType()+"\r\n\r\n");
fileExplain.append("\r\n");
fileDataLength += fileExplain.length();
if(uploadFile.getInStream()!=null){
fileDataLength += uploadFile.getFile().length();
}else{
fileDataLength += uploadFile.getData().length;
}
}
StringBuilder textEntity = new StringBuilder();
for (Map.Entry<String, String> entry : params.entrySet()) {//构造文本类型参数的实体数据
textEntity.append("--");
textEntity.append(BOUNDARY);
textEntity.append("\r\n");
textEntity.append("Content-Disposition: form-data; name=\""+ entry.getKey() + "\"\r\n\r\n");
textEntity.append(entry.getValue());
textEntity.append("\r\n");
}
//计算传输给服务器的实体数据总长度
int dataLength = textEntity.toString().getBytes().length + fileDataLength + endline.getBytes().length;
URL url = new URL(path);
int port = url.getPort()==-1 ? 80 : url.getPort();
Socket socket = new Socket(InetAddress.getByName(url.getHost()), port);
OutputStream outStream = socket.getOutputStream();
//下面完成HTTP请求头的发送
String requestmethod = "POST "+ url.getPath()+" HTTP/1.1\r\n";
outStream.write(requestmethod.getBytes());
String accept = "Accept: image/gif, image/jpeg, image/pjpeg, image/pjpeg, application/x-shockwave-flash, application/xaml+xml, application/vnd.ms-xpsdocument, application/x-ms-xbap, application/x-ms-application, application/vnd.ms-excel, application/vnd.ms-powerpoint, application/msword, */*\r\n";
outStream.write(accept.getBytes());
String language = "Accept-Language: zh-CN\r\n";
outStream.write(language.getBytes());
String contenttype = "Content-Type: multipart/form-data; boundary="+ BOUNDARY+ "\r\n";
outStream.write(contenttype.getBytes());
String contentlength = "Content-Length: "+ dataLength + "\r\n";
outStream.write(contentlength.getBytes());
String alive = "Connection: Keep-Alive\r\n";
outStream.write(alive.getBytes());
String host = "Host: "+ url.getHost() +":"+ port +"\r\n";
outStream.write(host.getBytes());
//写完HTTP请求头后根据HTTP协议再写一个回车换行
outStream.write("\r\n".getBytes());
//把所有文本类型的实体数据发送出来
outStream.write(textEntity.toString().getBytes());
//把所有文件类型的实体数据发送出来
for(FormFile uploadFile : files){
StringBuilder fileEntity = new StringBuilder();
fileEntity.append("--");
fileEntity.append(BOUNDARY);
fileEntity.append("\r\n");
fileEntity.append("Content-Disposition: form-data;name=\""+ uploadFile.getParameterName()+"\";filename=\""+ uploadFile.getFilname() + "\"\r\n");
fileEntity.append("Content-Type: "+ uploadFile.getContentType()+"\r\n\r\n");
outStream.write(fileEntity.toString().getBytes());
if(uploadFile.getInStream()!=null){
byte[] buffer = new byte[1024];
int len = 0;
while((len = uploadFile.getInStream().read(buffer, 0, 1024))!=-1){
outStream.write(buffer, 0, len);
}
uploadFile.getInStream().close();
}else{
outStream.write(uploadFile.getData(), 0, uploadFile.getData().length);
}
outStream.write("\r\n".getBytes());
}
//下面发送数据结束标志,表示数据已经结束
outStream.write(endline.getBytes());
BufferedReader reader = new BufferedReader(new InputStreamReader(socket.getInputStream()));
if(reader.readLine().indexOf("200")==-1){//读取web服务器返回的数据,判断请求码是否为200,如果不是200,代表请求失败
return false;
}
outStream.flush();
outStream.close();
reader.close();
socket.close();
return true;
}
/**
*单文件上传
* 提交数据到服务器
* @param path 上传路径(注:避免使用localhost或127.0.0.1这样的路径测试,因为它会指向手机模拟器,你可以使用http://www.itcast.cn或http://192.168.1.10:8080这样的路径测试)
* @param params 请求参数 key为参数名,value为参数值
* @param file 上传文件
*/
public static boolean post(String path, Map<String, String> params, FormFile file) throws Exception{
return post(path, params, new FormFile[]{file});
}
}
⑺ Android 使用OkhttpUtils上传图片
IMAGE_FILE_NAME这个确定是文件路径么?
那个其他我看不出来,我上传图片用的都是Xutils,你可以搜搜试试。
⑻ form表单上传图片,java后台转换(MultipartHttpServletRequest) request报错
我也想说“你确定别人可以”?
看源码就知道是不行的,你觉得把HttpServletRequest(父类)强转为MultipartHttpServletRequest(子类)可以吗?
你可以直接把文件作为一个参数注入进来。
⑼ 求高手解决form表单上传图片携带参数中文乱码问题...在线等
1、request.setCharacterEncoding("ISO8859_1");//处理乱码问题,未成功
这里的设置未必是这个,看你的前台是啥编码,中文一般是UTF8 GBK GB2312,你的具体是啥编码,看你的系统,我们以是UTF-8为例子,这里应该是
request.setCharacterEncoding("UTF-8")
2、下面的表单取的时候,这样取name = fi.getString("UTF-8")
⑽ android 怎么用二进制流上传图片与音频文件
QusetionForm qusetionForm = (QusetionForm)form; FormFile imageTopic= qusetionForm.getImageTopic(); String name=imageTopic.getFileName(); String url=(servlet.getServletConfig().getServletContext().getRealPath("\\")+name).replace('\\','/');