javahttp上傳文件到
文件從本地到伺服器的功能,其實是為了解決目前瀏覽器不支持獲取本地文件全路徑。不得已而想到上傳到伺服器的固定目錄,從而方便項目獲取文件,進而使程序支持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();
}
『貳』 java用戶HTTPURLConnection 上傳文件過程是先把文件寫入流中,然後上傳嗎,可以邊度邊傳嗎
那你就別用這種簡單流去發送,你把你數據分包,用包數據去傳
『叄』 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實現基於Http協議的大文件傳輸
雖然在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客戶端怎麼把本地的文件上傳到伺服器
String realpath = ServletActionContext.getServletContext().getRealPath("/upload") ;//獲取伺服器路徑
String[] targetFileName = uploadFileName;
for (int i = 0; i < upload.length; i++) {
File target = new File(realpath, targetFileName[i]);
FileUtils.File(upload[i], target);
//這是一個文件復制類File()裡面就是IO操作,如果你不用這個類也可以自己寫一個IO復制文件的類
}
其中private File[] upload;// 實際上傳文件
private String[] uploadContentType; // 文件的內容類型
private String[] uploadFileName; // 上傳文件名
這三個參數必須這樣命名,因為文件上傳控制項默認是封裝了這3個參數的,且在action裡面他們應有get,set方法
『陸』 java怎麼實現上傳文件到伺服器
common-fileupload是jakarta項目組開發的一個功能很強大的上傳文件組件
下面先介紹上傳文件到伺服器(多文件上傳):
import javax.servlet.*;
import javax.servlet.http.*;
import java.io.*;
import java.util.*;
import java.util.regex.*;
import org.apache.commons.fileupload.*;
public class upload extends HttpServlet {
private static final String CONTENT_TYPE = "text/html; charset=GB2312";
//Process the HTTP Post request
public void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
response.setContentType(CONTENT_TYPE);
PrintWriter out=response.getWriter();
try {
DiskFileUpload fu = new DiskFileUpload();
// 設置允許用戶上傳文件大小,單位:位元組,這里設為2m
fu.setSizeMax(2*1024*1024);
// 設置最多隻允許在內存中存儲的數據,單位:位元組
fu.setSizeThreshold(4096);
// 設置一旦文件大小超過getSizeThreshold()的值時數據存放在硬碟的目錄
fu.setRepositoryPath("c://windows//temp");
//開始讀取上傳信息
List fileItems = fu.parseRequest(request);
// 依次處理每個上傳的文件
Iterator iter = fileItems.iterator();
//正則匹配,過濾路徑取文件名
String regExp=".+////(.+)$";
//過濾掉的文件類型
String[] errorType={".exe",".com",".cgi",".asp"};
Pattern p = Pattern.compile(regExp);
while (iter.hasNext()) {
FileItem item = (FileItem)iter.next();
//忽略其他不是文件域的所有表單信息
if (!item.isFormField()) {
String name = item.getName();
long size = item.getSize();
if((name==null||name.equals("")) && size==0)
continue;
Matcher m = p.matcher(name);
boolean result = m.find();
if (result){
for (int temp=0;temp<ERRORTYPE.LENGTH;TEMP++){
if (m.group(1).endsWith(errorType[temp])){
throw new IOException(name+": wrong type");
}
}
try{
//保存上傳的文件到指定的目錄
//在下文中上傳文件至資料庫時,將對這里改寫
item.write(new File("d://" + m.group(1)));
out.print(name+" "+size+"");
}
catch(Exception e){
out.println(e);
}
}
else
{
throw new IOException("fail to upload");
}
}
}
}
catch (IOException e){
out.println(e);
}
catch (FileUploadException e){
out.println(e);
}
}
}
現在介紹上傳文件到伺服器,下面只寫出相關代碼:
以sql2000為例,表結構如下:
欄位名:name filecode
類型: varchar image
資料庫插入代碼為:PreparedStatement pstmt=conn.prepareStatement("insert into test values(?,?)");
代碼如下:
。。。。。。
try{
這段代碼如果不去掉,將一同寫入到伺服器中
//item.write(new File("d://" + m.group(1)));
int byteread=0;
//讀取輸入流,也就是上傳的文件內容
InputStream inStream=item.getInputStream();
pstmt.setString(1,m.group(1));
pstmt.setBinaryStream(2,inStream,(int)size);
pstmt.executeUpdate();
inStream.close();
out.println(name+" "+size+" ");
}
。。。。。。
這樣就實現了上傳文件至資料庫
『柒』 Java客戶端通過Http發送POST請求上傳文件
要按http的multi-part上傳的。接收端,再按multi-part解析成文件流
『捌』 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/
『玖』 怎麼用java程序實現上傳文件到指定的URL地址
//保存圖片
privatevoidsaveImg(HttpServletRequestrequest,FormFileimgFile,FileFormfileForm){
if(imgFile!=null&&imgFile.getFileSize()>0){
StringfileName=imgFile.getFileName();
StringsqlPath="img/"+fileName;
//圖片所在路徑
StringsavePath=request.getSession().getServletContext().getRealPath("/")+"img\"+fileName;
System.out.println(fileName);
System.out.println(sqlPath);
System.out.println(savePath);
HttpSessionsession=request.getSession();
session.setAttribute("savePath",savePath);
session.setMaxInactiveInterval(60*60);
//StringsavePath1=(String)session.getAttribute("savePath");
//資料庫
fileForm.getFile().setFileEmpPhoto(sqlPath);
//文件
try{
InputStreaminput=imgFile.getInputStream();
FileOutputStreamoutput=newFileOutputStream(savePath);
byte[]b=newbyte[1024];
while(input.read(b)!=-1){
output.write(b);
b=newbyte[1024];
}
output.close();
input.close();
}catch(FileNotFoundExceptione){
//TODOAuto-generatedcatchblock
e.printStackTrace();
}catch(IOExceptione){
//TODOAuto-generatedcatchblock
e.printStackTrace();
}
}
}
『拾』 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