
SpringBoot有它自己的接收请求的代码。下面就给大家详细介绍一下它是如何实现单个文件和多个文件上传的功能的。
首选做一个简单的案例,也就是单个文件上传的案例。(这个案例是基于SpringBoot上面的,所以大家首先得搭建好SpringBoot这个框架)
前台HTML代码:
[html] view plain copy
<html>
<body>
<form action="/upload" method="POST" enctype="multipart/form-data">
<input type="file" name="file"/>
<input type="submit" value="Upload"/>
</form>
</body>
</html>
后台接收代码:
[java] view plain copy
/
文件上传具体实现方法;
@param file
@return
/
@RequestMapping("/upload")
@ResponseBody
public String handleFileUpload(@RequestParam("file") MultipartFile file) {
if (!fileisEmpty()) {
try {
/
这段代码执行完毕之后,上传到了工程的跟路径; 大家自己扩散下思维,如果我们想把上传到
d:/files大家是否能实现呢? 等等;
这里只是简单一个例子,请自行参考,融入到实际中可能需要大家自己做一些思考,比如: 1、文件路径; 2、文件名;
3、文件格式; 4、文件大小的限制;
/
BufferedOutputStream out = new BufferedOutputStream(
new FileOutputStream(new File(
filegetOriginalFilename())));
Systemoutprintln(filegetName());
outwrite(filegetBytes());
outflush();
outclose();
} catch (FileNotFoundException e) {
eprintStackTrace();
return "上传失败," + egetMessage();
} catch (IOException e) {
eprintStackTrace();
return "上传失败," + egetMessage();
}
return "上传成功";
} else {
return "上传失败,因为文件是空的";
}
}
这样就可以实现对multipart/form-data类型文件的接收了。那如果是多个文件外加多个字段呢,下面接着看下一个多个文件上传的案例。
前台HTML界面:
[html] view plain copy
<!DOCTYPE html>
<html xmlns=">
xmlns:sec=">
<head>
<title>Hello World!</title>
</head>
<body>
<form method="POST" enctype="multipart/form-data" action="/batch/upload">
<p>文件1:<input type="text" name="id" /></p>
<p>文件2:<input type="text" name="name" /></p>
<p>文件3:<input type="file" name="file" /></p>
<p><input type="submit" value="上传" /></p>
</form>
</body>
</html>
后台接收代码:
[java] view plain copy
@RequestMapping(value = "/batch/upload", method = RequestMethodPOST)
@ResponseBody
public String handleFileUpload(>
Multipart>
List<MultipartFile> files = ((Multipart>
getFiles("file");
String name=paramsgetParameter("name");
Systemoutprintln("name:"+name);
String id=paramsgetParameter("id");
Systemoutprintln("id:"+id);
MultipartFile file = null;
BufferedOutputStream stream = null;
for (int i = 0; i < filessize(); ++i) {
file = filesget(i);
if (!fileisEmpty()) {
try {
byte[] bytes = filegetBytes();
stream = new BufferedOutputStream(new FileOutputStream(
new File(filegetOriginalFilename())));
streamwrite(bytes);
streamclose();
} catch (Exception e) {
stream = null;
return "You failed to upload " + i + " => "
+ egetMessage();
}
} else {
return "You failed to upload " + i
+ " because the file was empty";
}
}
return "upload successful";
}
这样就可以实现对多个文件的接收了功能了。
application/x->
文件的上传路径是你控制的
BufferedOutputStream out = new BufferedOutputStream(
new FileOutputStream(new File("/webapps/fileupload/upload/" + fileName)));
在网络编程过程中需要向服务器上传文件。Multipart/form-data是上传文件的一种方式。
Multipart/form-data其实就是浏览器用表单上传文件的方式。最常见的情境是:在写邮件时,向邮件后添加附件,附件通常使用表单添加,也就是用multipart/form-data格式上传到服务器。
表单形式上传附件
具体的步骤是怎样的呢?
首先,客户端和服务器建立连接(TCP协议)。
第二,客户端可以向服务器端发送数据。因为上传文件实质上也是向服务器端发送请求。
第三,客户端按照符合“multipart/form-data”的格式向服务器端发送数据。
既然Multipart/form-data格式就是浏览器用表单提交数据的格式,我们就来看看文件经过浏览器编码后是什么样子。
点击“Browse…”分别选择“unknowgif”和“unknow1gif”文件,点击“submit”按纽后,文件将被上传到服务器。
下面是服务器收到的数据:
服务器收到的数据
这是一个POST请求。所以数据是放在请求体内,而不是请求头内。
这行指出这个请求是“multipart/form-data”格式的,且“boundary”是 “---------------------------7db15a14291cce”这个字符串。
不难想象,“boundary”是用来隔开表单中不同部分数据的。例子中的表单就有 2 部分数据,用“boundary”隔开。“boundary”一般由系统随机产生,但也可以简单的用“-------------”来代替。
实际上,每部分数据的开头都是由"--" + boundary开始,而不是由 boundary 开始。仔细看才能发现下面的开头这段字符串实际上要比 boundary 多了个 “--”
紧接着 boundary 的是该部分数据的描述。
接下来才是数据。
“GIF”gif格式的文件头,可见,unknow1gif确实是gif格式。
在请求的最后,则是 "--" + boundary + "--" 表明表单的结束。
需要注意的是,在html协议中,用 “\r\n” 换行,而不是 “\n”。
下面的代码片断演示如何构造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;
>
//
// "std::wstring strPhotoPath" is the name of photo to upload
//
//
// uploaded photo form-part begin
//
std::wstring strMultipartFirst(L"--");
strMultipartFirst += strBoundary;
strMultipartFirst += L"\r\nContent-Disposition: form-data; name=\"pic\"; filename=";
strMultipartFirst += L"\"" + strPhotoPath + L"\"";
strMultipartFirst += L"\r\nContent-Type: image/jpeg\r\n\r\n";
//
// "std::wstring strTextContent" is the text to uploaded
//
//
// uploaded text form-part begin
//
std::wstring strMultipartInter(L"\r\n--");
strMultipartInter += strBoundary;
strMultipartInter += L"\r\nContent-Disposition: form-data; name=\"status\"\r\n\r\n";
std::wstring wstrPostDataUrlEncode(CEncodeTool::Encode_Url(strTextContent));
// add text content to send
strMultipartInter += wstrPostDataUrlEncode;
std::wstring strMultipartEnd(L"\r\n--");
strMultipartEnd += strBoundary;
strMultipartEnd += L"--\r\n";
//
// 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 = straMultipartFirstsize() + nPicFileLen + straMultipartIntersize() + straMultipartEndsize();
// Allocate the buffer to temporary store the data to send
PCHAR pchSendBuf = new CHAR[cSendBufLen];
memcpy(pchSendBuf, straMultipartFirstc_str(), straMultipartFirstsize());
memcpy(pchSendBuf + straMultipartFirstsize(), (const char )pchPicFileBuf, nPicFileLen);
memcpy(pchSendBuf + straMultipartFirstsize() + nPicFileLen, straMultipartInterc_str(), straMultipartIntersize());
memcpy(pchSendBuf + straMultipartFirstsize() + nPicFileLen + straMultipartIntersize(), straMultipartEndc_str(), straMultipartEndsize());
//
// send the request data
//
>
要将文件上传到URL,您可以使用cURL命令。cURL是一个开源的命令行工具,支持多个协议(如>
curl 中multipart/form-data和application/x->
FORM元素的enctype属性指定了表单数据向服务器提交时所采用的编码类型,默认的缺省值是“application/x->
以上就是关于如何用SpringBoot框架来接收multipart/form-data文件全部的内容,包括:如何用SpringBoot框架来接收multipart/form-data文件、为什么在form中加了enctype="multipart/form-data"后, 后台还是取不到上传的file文件在线等高手解释、java servlet 怎么获取表单里上传的文件的路径等相关内容解答,如果想了解更多相关内容,可以关注我们,你们的支持是我们更新的动力!
欢迎分享,转载请注明来源:内存溢出
微信扫一扫
支付宝扫一扫
评论列表(0条)