当前位置:首页 » 文件管理 » javapost文件上传

javapost文件上传

发布时间: 2022-07-16 06:22:04

1. java后台post方法上传文件

/** * 执行post请求并将返回内容转为json格式返回 */public static JsonObject doPost(String url, JsonObject message)throws WeiXinException {JsonObject jo = null;PrintWriter out = null;InputStream in = null;try {if (url.startsWith("https")){//https方式提交需要SSLContext sc = SSLContext.getInstance("SSL");sc.init(null, new TrustManager[] { new TrustAnyTrustManager() },new java.security.SecureRandom());URL console = new URL(url);HttpsURLConnection conn = (HttpsURLConnection) console.openConnection();conn.setSSLSocketFactory(sc.getSocketFactory());conn.setHostnameVerifier(new TrustAnyHostnameVerifier());conn.connect();in = conn.getInputStream();}else{in = new URL(url).openStream();}// 打开和URL之间的连接URLConnection conn = new URL(url).openConnection();// 设置通用的请求属性conn.setRequestProperty("accept", "*/*");conn.setRequestProperty("connection", "Keep-Alive");conn.setRequestProperty("user-agent","Mozilla/4.0 (compatible; MSIE 6.0; Windows NT 5.1;SV1)");// 发送POST请求必须设置如下两行conn.setDoOutput(true);conn.setDoInput(true);// 获取URLConnection对象对应的输出流out = new PrintWriter(conn.getOutputStream());// 发送请求参数out.print(message.toString());// flush输出流的缓冲out.flush();// POST请求out.flush();out.close();in = conn.getInputStream();jo = JSON.parse(getContext(in));doExeption(jo);} catch (MalformedURLException e) {e.printStackTrace();} catch (ProtocolException e) {e.printStackTrace();} catch (IOException e) {e.printStackTrace();} catch (KeyManagementException e) {e.printStackTrace();} catch (NoSuchAlgorithmException e) {e.printStackTrace();} finally {if (out != null) {out.flush();out.close();}if (in != null ){try {in.close();} catch (IOException e) {e.printStackTrace();}}}return jo;}

2. java程序digest认证后post上传文件,怎么搞

/** * 执行post请求并将返回内容转为json格式返回 */public static JsonObject doPost(String url, JsonObject message)throws WeiXinException {JsonObject jo = null;PrintWriter out = null;InputStream in = null;try {if (url.startsWith("https")){//https方式提交需要SSLContext sc = SSLContext.getInstance("SSL");sc.init(null, new TrustManager[] { new TrustAnyTrustManager() },new java.security.SecureRandom());URL console = new URL(url);HttpsURLConnection conn = (HttpsURLConnection) console.openConnection();conn.setSSLSocketFactory(sc.getSocketFactory());conn.setHostnameVerifier(new TrustAnyHostnameVerifier());conn.connect();in = conn.getInputStream();}else{in = new URL(url).openStream();}// 打开和URL之间的连接URLConnection conn = new URL(url).openConnection();// 设置通用的请求属性conn.setRequestProperty("accept", "*/*");conn.setRequestProperty("connection", "Keep-Alive");conn.setRequestProperty("user-agent","Mozilla/4.0 (compatible; MSIE 6.0; Windows NT 5.1;SV1)");// 发送POST请求必须设置如下两行conn.setDoOutput(true);conn.setDoInput(true);// 获取URLConnection对象对应的输出流out = new PrintWriter(conn.getOutputStream());// 发送请求参数out.print(message.toString());// flush输出流的缓冲out.flush();// POST请求out.flush();out.close();in = conn.getInputStream();jo = JSON.parse(getContext(in));doExeption(jo);} catch (MalformedURLException e) {e.printStackTrace();} catch (ProtocolException e) {e.printStackTrace();} catch (IOException e) {e.printStackTrace();} catch (KeyManagementException e) {e.printStackTrace();} catch (NoSuchAlgorithmException e) {e.printStackTrace();} finally {if (out != null) {out.flush();out.close();}if (in != null ){try {in.close();} catch (IOException e) {e.printStackTrace();}}}return jo;}

3. java中怎么把文件上传到服务器的指定路径

文件从本地到服务器的功能,其实是为了解决目前浏览器不支持获取本地文件全路径。不得已而想到上传到服务器的固定目录,从而方便项目获取文件,进而使程序支持EXCEL批量导入数据。

java中文件上传到服务器的指定路径的代码:

在前台界面中输入:

<form method="post" enctype="multipart/form-data" action="../manage/excelImport.do">

请选文件:<input type="file" name="excelFile">

<input type="submit" value="导入" onclick="return impExcel();"/>

</form>

action中获取前台传来数据并保存

/**

* excel 导入文件

* @return

* @throws IOException

*/

@RequestMapping("/usermanager/excelImport.do")

public String excelImport(

String filePath,

MultipartFile excelFile,HttpServletRequest request) throws IOException{

log.info("<<<<<<action:{} Method:{} start>>>>>>","usermanager","excelImport" );

if (excelFile != null){

String filename=excelFile.getOriginalFilename();

String a=request.getRealPath("u/cms/www/201509");

SaveFileFromInputStream(excelFile.getInputStream(),request.getRealPath("u/cms/www/201509"),filename);//保存到服务器的路径

}

log.info("<<<<<<action:{} Method:{} end>>>>>>","usermanager","excelImport" );

return "";

}

/**

* 将MultipartFile转化为file并保存到服务器上的某地

*/

public void SaveFileFromInputStream(InputStream stream,String path,String savefile) throws IOException

{

FileOutputStream fs=new FileOutputStream( path + "/"+ savefile);

System.out.println("------------"+path + "/"+ savefile);

byte[] buffer =new byte[1024*1024];

int bytesum = 0;

int byteread = 0;

while ((byteread=stream.read(buffer))!=-1)

{

bytesum+=byteread;

fs.write(buffer,0,byteread);

fs.flush();

}

fs.close();

stream.close();

}

4. java发送post请求传送文本和文件

kankan

5. java http post 同时发送文件流与数据

您好,提问者:
首先表单、文件同时发送那么肯定是可以的,关于获取的话很难了,因为发送文件的话form必须设置为:multipart/form-data数据格式,默认为:application/x-www-form-urlencoded表单格式。我们称之为二进制流和普通数据流。

刚才说了<form的entype要改为multipart/form-data才能进行发送文件,那么这个时候你表单的另外数据就也会被当成二进制一起发送到服务端。

获取读取过来的内容如下:

//拿到用户传送过来的字节流
InputStreamis=request.getInputStream();
byte[]b=newbyte[1024];
intlen=0;
while((len=is.read(b))!=-1){
System.out.println(newString(b,0,len));
}

上面如图的代码,我们发现发送过来的表单数据跟文件数据是混乱的,我们根本没办法解析(很麻烦),这个时候我们就需要用到第三方辅助(apache 提供的fileupload.jar)来进行获取。

这个网上有很多代码的,如果有什么不明白可以去自行网络,或者追问,我这里只是给你提供的思路,希望理解,谢谢!

6. java客户端通过http发送POST请求上传文件

这样的写法,是直接socket的做法。

如果是HTTP的,要按HTTP的协议进行。先了解一下multi-part的post

7. Java客户端通过Http发送POST请求上传文件

要按http的multi-part上传的。接收端,再按multi-part解析成文件流

8. javaEE 如何将ID post上传

用httpclient这个jar包

/**
*连接超时
*/
_TIME_OUT=1000*30;


/**
*响应超时
*/
publicstaticfinalintSO_TIMEOUT=1000*30;

/**
*发一起个Post请求,简单的Text方式
*@paramurl 请求URL
*@paramparameters 请求参数
*@paramencoding 字符编码
*@return
*@throwsException
*/
publicstaticStringpost(Stringurl,List<NameValuePair>parameters,Stringencoding)throwsException{
BasicHttpParamshttpParameters=newBasicHttpParams();
HttpConnectionParams.setConnectionTimeout(httpParameters,CONNECTION_TIME_OUT);
HttpConnectionParams.setSoTimeout(httpParameters,SO_TIMEOUT);
HttpClienthttpClient=newDefaultHttpClient(httpParameters);

HttpPostpost=newHttpPost(url);
HttpResponseresponse;
try{
UrlEncodedFormEntityencode=newUrlEncodedFormEntity(parameters,encoding);
post.setEntity(encode);
response=httpClient.execute(post);
returnEntityUtils.toString(response.getEntity());
}catch(Exceptione){
throwe;
}
}



9. java web怎么实现文件上传到服务器

/**
* 上传到本地
* @param uploadFile
* @param request
* @return
*/
@RequestMapping("/upload")
@ResponseBody
public Map<String, Object> uploadApkFile(@RequestParam("uploadUpdateHistoryName") MultipartFile uploadFile,
HttpServletRequest request) {
Map<String, Object> map = new HashMap<>();
// 上传文件校验,包括上传文件是否为空、文件名称是否为空、文件格式是否为APK。
if (uploadFile == null) {
map.put("error", 1);
map.put("msg", "上传文件不能为空");
return map;
}
String originalFilename = uploadFile.getOriginalFilename();
if (StringUtils.isEmpty(originalFilename)) {
map.put("error", 1);
map.put("msg", "上传文件名称不能为空");
return map;
}
String extName = originalFilename.substring(originalFilename.lastIndexOf(".") + 1);
if (extName.toUpperCase().indexOf("APK") < 0) {
map.put("error", 1);
map.put("msg", "上传文件格式必须为APK");
return map;
}

String path = request.getSession().getServletContext().getRealPath("upload");
String fileName = uploadFile.getOriginalFilename();
File targetFile = new File(path, fileName);
if (!targetFile.exists()) {
targetFile.mkdirs();
}
// 保存
String downLoadUrl = null;
try {
uploadFile.transferTo(targetFile);
downLoadUrl = request.getContextPath() + "/upload/" + fileName;
map.put("error", 0);
map.put("downLoadUrl", downLoadUrl);
map.put("msg", "上传文件成功");
return map;
} catch (Exception e) {
e.printStackTrace();
map.put("error", 1);
map.put("msg", "上传文件失败");
return map;
}
}

//上传文件
$('#btnUpload').bind('click',function(){
// var formdata= $('#uploadForm').serializeJSON();
var formdata = new FormData($( "#uploadForm" )[0]);
$.ajax({
url:"upload.do",
data:formdata,
async: false,
cache: false,
processData:false,
contentType:false,
// dataType:'json',
type:'post',
success:function(value){
if(value.error==0){
$('#downLoadUrlId').val(value.downLoadUrl);
$.messager.alert('提示',value.msg);
$('#uploadWindow').window('close');
}else{
$.messager.alert('提示',value.msg);
}
}
});
});

<div id="uploadWindow" class="easyui-window" title="apk上传"
style="width: 230px;height: 100px" data-options="closed:true">
<form id="uploadForm" enctype="multipart/form-data">
<td><input type ="file" style="width:200px;" name = "uploadUpdateHistoryName"></td>
</form>
<button id="btnUpload" type="button">上传Apk</button>
</div>

java js html

热点内容
安卓数据线怎么接蓝牙 发布:2025-01-22 12:07:29 浏览:229
扣扣账号多少次密码不正确会被封 发布:2025-01-22 12:07:19 浏览:400
python是32位还是64位 发布:2025-01-22 11:51:41 浏览:894
铃声多多缓存文件夹 发布:2025-01-22 11:51:39 浏览:724
java按键精灵 发布:2025-01-22 11:49:31 浏览:81
python配色 发布:2025-01-22 11:46:40 浏览:613
安卓如何使用屏幕录制 发布:2025-01-22 11:46:36 浏览:777
phpencoding 发布:2025-01-22 11:46:35 浏览:257
安卓235玩什么 发布:2025-01-22 11:37:40 浏览:217
c语言计算个人所得税 发布:2025-01-22 11:28:49 浏览:735