如何使用POST上传的二进制数据
发布网友
发布时间:2022-04-25 19:33
我来回答
共2个回答
热心网友
时间:2022-06-16 18:32
这个不就是文件上传嘛
给你个servlet3.0的文件上传
页面表单
<form action="sf" enctype="multipart/form-data" method="get">
username: <input type="text" name="username" /><br>
file: <input type="file" name="filename" /><br>
<input type="submit" value="Submit" />
</form>
servlet头注解配置
@WebServlet("/sf")
@MultipartConfig
public class SingleFileUpload extends HttpServlet {
doPost 方法
Java code
?
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
Enumeration<String> heads = request.getHeaderNames();
System.out.println("request.getHeaderNames()");
while (heads.hasMoreElements()) {
String header = heads.nextElement();
System.out.println(header + "=" + request.getHeader(header));
}
Part part = request.getPart("filename");
Collection<String> headerNames = part.getHeaderNames();
System.out.println("part.getHeaderNames()");
for (String header : headerNames) {
System.out.println(header + "=" + part.getHeader(header));
}
InputStream is = part.getInputStream();
String filename = new String(getFilename(part).getBytes(), "UTF-8");
File file = new File("D:\\fileupload");
if (!file.exists() || !file.isDirectory()) {
file.mkdir();
}
FileOutputStream fos = new FileOutputStream(new File(file + File.separator + filename));
byte[] buf = new byte[1024];
while (is.read(buf) != -1) {
fos.write(buf);
}
fos.flush();
fos.close();
is.close();
PrintWriter out = response.getWriter();
out.println("file upload success");
}
public String getFilename(Part part) {
String contentDispositionHeader = part.getHeader("content-disposition");
String[] elements = contentDispositionHeader.split(";");
for (String element : elements) {
if (element.trim().startsWith("filename")) {
return element.substring(element.indexOf('=') + 1).trim().replace("\"", "");
}
}
return null;
}
热心网友
时间:2022-06-16 18:32
可使用android自带的httpclient框架实现向服务器发起get或post请求,以下为完整的示例代码:
1. GET 方式传递参数
//先将参数放入List,再对参数进行URL编码
List<BasicNameValuePair> params = new LinkedList<BasicNameValuePair>();
params.add(new BasicNameValuePair("param1", "数据")); //增加参数1
params.add(new BasicNameValuePair("param2", "value2"));//增加参数2
String param = URLEncodedUtils.format(params, "UTF-8");//对参数编码
String baseUrl = "服务器接口完整URL";
HttpGet getMethod = new HttpGet(baseUrl + "?" + param);//将URL与参数拼接
HttpClient httpClient = new DefaultHttpClient();