javahttp文件上傳
互聯網項目一般會有單獨的伺服器存放靜態資源,圖片就是一種靜態資源,在這里就是區別於項目部署的另一台伺服器。這時候你項目裡面都是使用相對路徑,像你上面所說的常量/opt/upload/這種做法是正確的,上傳圖片的時候,常見的有使用日期分目錄存儲的,如/opt/upload/2014/11/03/***.jpg,對於圖片的路徑,資料庫里一般來說保存到2014/11/03/***.jpg就可以了。這是存圖片。
取圖片,一般來說資源都必須發布服務才能讓外網訪問。例如,你可以在你項目中寫個servlet用來讀取圖片,如下面的服務地址http://ip:port/projectname/image/2014/11/03/***.jpg,其中2014前面的路徑是固定的,後面的是你資料庫里存儲的圖片地址,這時你頁面代碼裡面只需固定前綴http://ip:port/projectname/image + 圖片相對地址則可將圖片讀出來。
上面這種方法用的其實比較少,一般來說靜態伺服器都會部署一個web容器,然後使用單獨的域名,打個比方,你在靜態伺服器上有個tomcat,目錄/opt/tomcat/webapp/staticprojectname,staticprojectname是工程名,然後在上傳的所有圖片在staticprojectname下面,例如/opt/tomcat/webapp/staticprojectname/2014/11/03/***.jpg,然後在你原工程裡面直接使用http://靜態服務ip:port/staticprojectname/2014/11/03/***.jpg就可以訪問到圖片了,同樣的在你代碼裡面2014前面的地址是固定的,配置成常量,後面的則是資料庫里存的圖片相對地址。
說了這么多,有點亂,希望你能明白
Ⅱ java後台文件上傳到資源伺服器上
package com.letv.dir.cloud.util;import com.letv.dir.cloud.controller.DirectorWatermarkController;import org.slf4j.Logger;import org.slf4j.LoggerFactory;import java.io.*;import java.net.HttpURLConnection;import java.net.MalformedURLException;import java.net.URL;/** * Created by xijunge on 2016/11/24 0024. */public class HttpRequesterFile { private static final Logger log = LoggerFactory.getLogger(HttpRequesterFile.class); private static final String TAG = "uploadFile"; private static final int TIME_OUT = 100 * 1000; // 超時時間 private static final String CHARSET = "utf-8"; // 設置編碼 /** * 上傳文件到伺服器 * * @param file * 需要上傳的文件 * @param RequestURL * 文件伺服器的rul * @return 返回響應的內容 * */ public static String uploadFile(File file, String RequestURL) throws IOException {
String result = null;
String BOUNDARY = "letv"; // 邊界標識 隨機生成 String PREFIX = "--", LINE_END = "\r\n";
String CONTENT_TYPE = "multipart/form-data"; // 內容類型 try {
URL url = new URL(RequestURL);
HttpURLConnection conn = (HttpURLConnection) url.openConnection();
conn.setReadTimeout(TIME_OUT);
conn.setConnectTimeout(TIME_OUT);
conn.setDoInput(true); // 允許輸入流 conn.setDoOutput(true); // 允許輸出流 conn.setUseCaches(false); // 不允許使用緩存 conn.setRequestMethod("POST"); // 請求方式 conn.setRequestProperty("Charset", CHARSET); // 設置編碼 conn.setRequestProperty("connection", "keep-alive");
conn.setRequestProperty("Content-Type", CONTENT_TYPE + ";boundary=" + BOUNDARY);
Ⅲ Java利用HttpURLConnection發送post請求上傳文件
在頁面里實現上傳文件不是什麼難事 寫個form 加上enctype = multipart/form data 在寫個接收的就可以了 沒租褲什麼難的 如果要用 HttpURLConnection來實現文件上傳 還真有點搞頭 : )
先寫個servlet把接收到的 HTTP 信息保存在一個文件中 看一下 form 表單到底封裝了什麼樣的信息
Java代碼
public void doPost(HttpServletRequest request HttpServletResponse response)
throws ServletException IOException {
//獲取輸入流 是HTTP協議中的實體內容
ServletInputStream in=request getInputStream();
//緩沖區
byte buffer[]=new byte[ ];
FileOutputStream out=new FileOutputStream( d:\test log );
int len=sis read(buffer );
//把流里的信息循環讀入到file log文件中
while( len!= ){
out write(buffer len);
len=in readLine(buffer );
}
out close();
in close();
}
來一個form表單
<form name= upform action= upload do method= POST
enctype= multipart/form data >
參數<input type= text name= username /><br/>
文件 <input type= file name= file /><br/>
文件 <input type= file name= file /><br/>
<input type= submit value= Submit />
<br />
</form>
假如我參數寫的內容是hello word 然後二個文件是二個簡單的txt文件梁譽 上傳後test log里如下
Java代碼
da e c
Content Disposition: form data; name= username
hello word
da e c
Content Disposition: form data; name= file ; filename= D:haha txt
Content Type: text/plain
haha
hahaha
da e c
Content Disposition: form data; name= file ; filename= D:huhu txt
Content Type: text/plain
messi
huhu
da e c
研究下規律發現有如下幾點特徵
第一行是 d b bc 作為分隔符 然後是 回車換行符 這個 d b bc 分隔符瀏覽器是隨機生成的
第二行是Content Disposition: form data; name= file ; filename= D:huhu txt ;name=對應input的name值 filename對應要上傳的文件名(包括路徑在內)
第三行如果是文件就有Content Type: text/plain 這里上傳的是txt文件所以是text/plain 如果上穿的是jpg圖片的話就是image/jpg了 可以自己試試看看
然後就是回弊渣簡車換行符
在下就是文件或參數的內容或值了 如 hello word
最後一行是 da e c 注意最後多了二個 ;
有了這些就可以使用HttpURLConnection來實現上傳文件功能了
Java代碼 public void upload(){
List<String> list = new ArrayList<String>(); //要上傳的文件名 如 d:haha doc 你要實現自己的業務 我這里就是一個空list
try {
String BOUNDARY = d a d c ; // 定義數據分隔線
URL url = new URL( );
HttpURLConnection conn = (HttpURLConnection) url openConnection();
// 發送POST請求必須設置如下兩行
conn setDoOutput(true);
conn setDoInput(true);
conn setUseCaches(false);
conn setRequestMethod( POST );
conn setRequestProperty( connection Keep Alive );
conn setRequestProperty( user agent Mozilla/ (patible; MSIE ; Windows NT ; SV ) );
conn setRequestProperty( Charsert UTF );
conn setRequestProperty( Content Type multipart/form data; boundary= + BOUNDARY);
OutputStream out = new DataOutputStream(conn getOutputStream());
byte[] end_data = ( + BOUNDARY + ) getBytes();// 定義最後數據分隔線
int leng = list size();
for(int i= ;i<leng;i++){
String fname = list get(i);
File file = new File(fname);
StringBuilder *** = new StringBuilder();
*** append( );
*** append(BOUNDARY);
*** append( );
*** append( Content Disposition: form data;name= file +i+ ;filename= + file getName() + );
*** append( Content Type:application/octet stream );
byte[] data = *** toString() getBytes();
out write(data);
DataInputStream in = new DataInputStream(new FileInputStream(file));
int bytes = ;
byte[] bufferOut = new byte[ ];
while ((bytes = in read(bufferOut)) != ) {
out write(bufferOut bytes);
}
out write( getBytes()); //多個文件時 二個文件之間加入這個
in close();
}
out write(end_data);
out flush();
out close();
// 定義BufferedReader輸入流來讀取URL的響應
BufferedReader reader = new BufferedReader(new InputStreamReader(conn getInputStream()));
String line = null;
while ((line = reader readLine()) != null) {
System out println(line);
}
} catch (Exception e) {
System out println( 發送POST請求出現異常! + e);
e printStackTrace();
}
lishixin/Article/program/Java/hx/201311/27114
Ⅳ java用戶HTTPURLConnection 上傳文件過程是先把文件寫入流中,然後上傳嗎,可以邊度邊傳嗎
那你就別用這種簡單流去發送,你把你數據分包,用包數據去傳
Ⅳ httpclient 怎麼實現多文件上傳 c/s java
雖然在JDK的java.net包中已經提供了訪問HTTP協議的基本功能,但是對於大部分應用程序來說,JDK庫本身提供的功能還不夠豐富和靈活。HttpClient是ApacheJakartaCommon下的子項目,用來提供高效的、最新的、功能豐富的支持HTTP協議的客戶端編程工具包,並且它支持HTTP協議最新的版本和建議。以下是簡單的post例子:Stringurl="bbslogin2.php";PostMethodpostMethod=newPostMethod(url);//填入各個表單域的值NameValuePair[]data={newNameValuePair("id","youUserName"),newNameValuePair("passwd","yourPwd")};//將表單的值放入postMethod中postMethod.setRequestBody(data);//執行postMethodintstatusCode=httpClient.executeMethod(postMethod);//HttpClient對於要求接受後繼服務的請求,象POST和PUT等不能自動處理轉發//301或者302if(statusCode==HttpStatus.SC_MOVED_PERMANENTLY||statusCode==HttpStatus.SC_MOVED_TEMPORARILY){//從頭中取出轉向的地址HeaderlocationHeader=postMethod.getResponseHeader("location");Stringlocation=null;if(locationHeader!=null){location=locationHeader.getValue();System.out.println("Thepagewasredirectedto:"+location);}else{System.err.println("Locationfieldvalueisnull.");}return;}詳情見:/developerworks/cn/opensource/os-httpclient/
Ⅵ Java客戶端通過Http發送POST請求上傳文件
要按http的multi-part上傳的。接收端,再按multi-part解析成文件流
Ⅶ java實現文件上傳,代碼盡量簡潔~~~~~·
普通方法實現任意上傳?本地文件?本地文件直接用FileInputStream即可。
jspsmartupload需要在提交的form表單中添加一個屬性,具體內容忘了=。=
Ⅷ java 如何實現 http協議傳輸
Java 6 提供了一個輕量級的純 Java Http 伺服器的實現。下面是一個簡單的例子:
public static void main(String[] args) throws Exception{
HttpServerProvider httpServerProvider = HttpServerProvider.provider();
InetSocketAddress addr = new InetSocketAddress(7778);
HttpServer httpServer = httpServerProvider.createHttpServer(addr, 1);
httpServer.createContext("/myapp/", new MyHttpHandler());
httpServer.setExecutor(null);
httpServer.start();
System.out.println("started");
}
static class MyHttpHandler implements HttpHandler{
public void handle(HttpExchange httpExchange) throws IOException {
String response = "Hello world!";
httpExchange.sendResponseHeaders(200, response.length());
OutputStream out = httpExchange.getResponseBody();
out.write(response.getBytes());
out.close();
}
}
然後,在瀏覽器中訪問 http://localhost:7778/myapp/
Ⅸ http如何實現同時發送文件和報文(用java實現)
你用的servlet還是別的框架?
選POST
選form-data
選body
選File
選文件
Send
// commonsfileupload組件的情況下,servlet接收的數據只能是type=file表單元素類型,那麼獲取type=text類型,就可以使用parseRequest(request)來獲取list,fileitem,判斷isFormField,為true非file類型的。就可以處理了。下面是處理的部分代碼:
DiskFileItemFactoryfactory=newDiskFileItemFactory();factory.setSizeThreshold(1024*1024);
Stringdirtemp="c:";
Filefiledir=newFile(dirtemp+"filetemp");
Stringstr=null;if(!filedir.exists())filedir.mkdir();factory.setRepository(filedir);
ServletFileUploapload=newServletFileUpload(factory);
Listlist=upload.parseRequest(request);for(
inti=0;i<list.size();i++)
{
FileItemitem=(FileItem)list.get(i);
if(item.isFormField()){
System.out.println(item.getString());
}else{
Stringfilename=item.getName();
item.write(newFile(request.getRealPath(dir),filename));
}
}
Ⅹ 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