A. form表單怎麼能直接提交ftp伺服器上,把文件上傳到ftp伺服器上!
沒辦法直接傳的!
你只能用表單先傳到web伺服器上,
然後再從web伺服器上傳到FTP上!(可以自己寫一個服務程序)
B. springmvc 怎麼將文件上傳到linux伺服器
Spring MVC為文件上傳提供了直接的支持,這種支持是通過即插即用的MultipartResolver實現的。Spring使用Jakarta Commons FileUpload 技術實現了一個MultipartResolver實現類:CommonsMultipartResolver。
Spring MVC上下文中默認沒有裝配MultipartResolver,因此默認情況下不能處理文件的上傳工作。如果想要使用Spring的文件上傳功能,需要先在上下文中配置MultipartResolver。
第一步:配置MultipartResolver
使用CommonsMultipartResolver配置一個MultipartResolver解析器:
<bean id="multipartResolver" class="org.springframework.web.multipart.commons.CommonsMultipartResolver"
p:defaultEncoding="UTF-8"
p:maxUploadSize="5242880"
p:uploadTempDir="upload/temp"
/>
defaultEncoding必須和用戶JSP的pageEncoding屬性一致,以便正確讀取表單的內容。uploadTempDir是文件上傳過程所使用的臨時目錄,文件上傳完成後,臨時目錄中的臨時文件會被自動清除。
第二步:編寫文件上傳表單頁面和控制器
JSP頁面如下:
<%@ page language="java" import="java.util.*" pageEncoding="utf-8"%>
<%
String path = request.getContextPath();
String basePath = request.getScheme()+"://"+request.getServerName()+":"+request.getServerPort()+path+"/";
%>
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN">
<html>
<head>
<base href="<%=basePath%>">
<title>My JSP 'index.jsp' starting page</title>
<meta http-equiv="pragma" content="no-cache">
<meta http-equiv="cache-control" content="no-cache">
<meta http-equiv="expires" content="0">
<meta http-equiv="keywords" content="keyword1,keyword2,keyword3">
<meta http-equiv="description" content="This is my page">
</head>
<body>
<h1>選擇上傳文件</h1>
<form action="<%=basePath%>user/upload.do" method="post" enctype="multipart/form-data">
文件名:<input type="text" name="name" /><br/>
<input type="file" name="file" /><br/>
<input type="submit" />
</form>
</body>
</html>
注意:負責上傳的表單和一般表單有一些區別,表單的編碼類型必須是"Multipart/form-data"
控制器UserController如下:
package com.web;
import java.io.File;
import java.io.IOException;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.multipart.MultipartFile;
@Controller
@RequestMapping(value = "/user")
public class UserController {
@RequestMapping(value = "/upload.do")
public String updateThumb(@RequestParam("name") String name,
@RequestParam("file") MultipartFile file)
throws IllegalStateException, IOException {
if (!file.isEmpty()) {
file.transferTo(new File("d:/temp/"
+ name
+ file.getOriginalFilename().substring(
file.getOriginalFilename().lastIndexOf("."))));
return "redirect:success.html";
} else {
return "redirect:fail.html";
}
}
}
Spring MVC會將上傳文件綁定到MultipartFile對象中。MultipartFile提供了獲取上傳文件內容、文件名等內容,通過transferTo方法還可將文件存儲到硬體中,具體說明如下:
byte[] getBytes() :獲取文件數據
String getContentType():獲取文件MIME類型,如image/pjpeg、text/plain等
InputStream getInputStream():獲取文件流
String getName():獲取表單中文件組件的名字
String getOriginalFilename():獲取上傳文件的原名
long getSize():獲取文件的位元組大小,單位為byte
boolean isEmpty():是否有上傳的文件
void transferTo(File dest):可以使用該文件將上傳文件保存到一個目標文件中
源碼:uploadtest.zip
C. 如何使用multipart/form-data格式上傳文件
在網路編程過程中需要向伺服器上傳文件。Multipart/form-data是上傳文件的一種方式。
Multipart/form-data其實就是瀏覽器用表單上傳文件的方式。最常見的情境是:在寫郵件時,向郵件後添加附件,附件通常使用表單添加,也就是用multipart/form-data格式上傳到伺服器。
表單形式上傳附件
具體的步驟是怎樣的呢?
首先,客戶端和伺服器建立連接(TCP協議)。
第二,客戶端可以向伺服器端發送數據。因為上傳文件實質上也是向伺服器端發送請求。
第三,客戶端按照符合「multipart/form-data」的格式向伺服器端發送數據。
既然Multipart/form-data格式就是瀏覽器用表單提交數據的格式,我們就來看看文件經過瀏覽器編碼後是什麼樣子。
這行指出這個請求是「multipart/form-data」格式的,且「boundary」是 「---------------------------7db15a14291cce」這個字元串。
不難想像,「boundary」是用來隔開表單中不同部分數據的。例子中的表單就有 2 部分數據,用「boundary」隔開。「boundary」一般由系統隨機產生,但也可以簡單的用「-------------」來代替。
實際上,每部分數據的開頭都是由"--" + boundary開始,而不是由 boundary 開始。仔細看才能發現下面的開頭這段字元串實際上要比 boundary 多了個 「--」
緊接著 boundary 的是該部分數據的描述。
接下來才是數據。
「GIF」gif格式圖片的文件頭,可見,unknow1.gif確實是gif格式圖片。
在請求的最後,則是 "--" + boundary + "--" 表明表單的結束。
需要注意的是,在html協議中,用 「 」 換行,而不是 「 」。
下面的代碼片斷演示如何構造multipart/form-data格式數據,並上傳圖片到伺服器。
//---------------------------------------
// this is the demo code of using multipart/form-data to upload text and photos.
// -use WinInet APIs.
//
//
// connection handlers.
//
HRESULT hr;
HINTERNET m_hOpen;
HINTERNET m_hConnect;
HINTERNET m_hRequest;
//
// make connection.
//
...
//
// form the content.
//
std::wstring strBoundary = std::wstring(L"------------------");
std::wstring wstrHeader(L"Content-Type: multipart/form-data, boundary=");
wstrHeader += strBoundary;
HttpAddRequestHeaders(m_hRequest, wstrHeader.c_str(), DWORD(wstrHeader.size()), HTTP_ADDREQ_FLAG_ADD);
//
// "std::wstring strPhotoPath" is the name of photo to upload.
//
//
// uploaded photo form-part begin.
//
std::wstring strMultipartFirst(L"--");
strMultipartFirst += strBoundary;
strMultipartFirst += L" Content-Disposition: form-data; name="pic"; filename=";
strMultipartFirst += L""" + strPhotoPath + L""";
strMultipartFirst += L" Content-Type: image/jpeg ";
//
// "std::wstring strTextContent" is the text to uploaded.
//
//
// uploaded text form-part begin.
//
std::wstring strMultipartInter(L" --");
strMultipartInter += strBoundary;
strMultipartInter += L" Content-Disposition: form-data; name="status" ";
std::wstring wstrPostDataUrlEncode(CEncodeTool::Encode_Url(strTextContent));
// add text content to send.
strMultipartInter += wstrPostDataUrlEncode;
std::wstring strMultipartEnd(L" --");
strMultipartEnd += strBoundary;
strMultipartEnd += L"-- ";
//
// open photo file.
//
// ws2s(std::wstring)
// -transform "strPhotopath" from unicode to ansi.
std::ifstream *pstdofsPicInput = new std::ifstream;
pstdofsPicInput->open((ws2s(strPhotoPath)).c_str(), std::ios::binary|std::ios::in);
pstdofsPicInput->seekg(0, std::ios::end);
int nFileSize = pstdofsPicInput->tellg();
if(nPicFileLen == 0)
{
return E_ACCESSDENIED;
}
char *pchPicFileBuf = NULL;
try
{
pchPicFileBuf = new char[nPicFileLen];
}
catch(std::bad_alloc)
{
hr = E_FAIL;
}
if(FAILED(hr))
{
return hr;
}
pstdofsPicInput->seekg(0, std::ios::beg);
pstdofsPicInput->read(pchPicFileBuf, nPicFileLen);
if(pstdofsPicInput->bad())
{
pstdofsPicInput->close();
hr = E_FAIL;
}
delete pstdofsPicInput;
if(FAILED(hr))
{
return hr;
}
// Calculate the length of data to send.
std::string straMultipartFirst = CEncodeTool::ws2s(strMultipartFirst);
std::string straMultipartInter = CEncodeTool::ws2s(strMultipartInter);
std::string straMultipartEnd = CEncodeTool::ws2s(strMultipartEnd);
int cSendBufLen = straMultipartFirst.size() + nPicFileLen + straMultipartInter.size() + straMultipartEnd.size();
// Allocate the buffer to temporary store the data to send.
PCHAR pchSendBuf = new CHAR[cSendBufLen];
memcpy(pchSendBuf, straMultipartFirst.c_str(), straMultipartFirst.size());
memcpy(pchSendBuf + straMultipartFirst.size(), (const char *)pchPicFileBuf, nPicFileLen);
memcpy(pchSendBuf + straMultipartFirst.size() + nPicFileLen, straMultipartInter.c_str(), straMultipartInter.size());
memcpy(pchSendBuf + straMultipartFirst.size() + nPicFileLen + straMultipartInter.size(), straMultipartEnd.c_str(), straMultipartEnd.size());
//
// send the request data.
//
HttpSendRequest(m_hRequest, NULL, 0, (LPVOID)pchSendBuf, cSendBufLen)
D. php上傳文件到伺服器
1、通過PHP,可以把文件上傳到伺服器。創建一個文件上傳表單,下面這個供上傳文件的 HTML 表單:
<html>
<body>
<formaction="upload_file.php"method="post"
enctype="multipart/form-data">
<labelfor="file">Filename:</label>
<inputtype="file"name="file"id="file"/>
<br/>
<inputtype="submit"name="submit"value="Submit"/>
</form>
</body>
</html>
2、創建上傳腳本,命名為"upload_file.php" 文件含有供上傳文件的代碼:
<?php
if($_FILES["file"]["error"]>0)
{
echo"Error:".$_FILES["file"]["error"]."<br/>";
}
else
{
echo"Upload:".$_FILES["file"]["name"]."<br/>";
echo"Type:".$_FILES["file"]["type"]."<br/>";
echo"Size:".($_FILES["file"]["size"]/1024)."Kb<br/>";
echo"Storedin:".$_FILES["file"]["tmp_name"];
}
?>
註:通過使用 PHP 的全局數組 「$_FILES」,就可以實現從客戶計算機向遠程伺服器上傳文件。