當前位置:首頁 » 文件管理 » 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

熱點內容
ibatissqlnotin 發布:2025-01-22 14:42:25 瀏覽:326
java電子書軟體下載 發布:2025-01-22 14:41:41 瀏覽:729
tomcat遠程訪問 發布:2025-01-22 14:41:33 瀏覽:960
a演算法解決八數碼問題 發布:2025-01-22 14:32:39 瀏覽:273
python編譯exe 發布:2025-01-22 14:31:11 瀏覽:451
現在密碼箱多少錢 發布:2025-01-22 14:30:26 瀏覽:970
aspnet訪問access 發布:2025-01-22 14:14:15 瀏覽:924
鴻蒙系統和安卓的哪個耗電 發布:2025-01-22 14:12:46 瀏覽:577
上海大眾壓縮機 發布:2025-01-22 14:02:31 瀏覽:48
讀取excel的sql 發布:2025-01-22 13:59:58 瀏覽:865