1.首先需要上传客户端,与接收文件的服务端
代码如下
@RequestMapping("/receive")
public String receive(HttpServletRequest request, HttpServletResponse response) throws Exception {
// 判断enctype属性是否为multipart/form-data
boolean isMultipart = ServletFileUpload.isMultipartContent(request);
if (!isMultipart)
throw new IllegalArgumentException(
"上传内容不是有效的multipart/form-data类型.");
// Create a factory for disk-based file items
DiskFileItemFactory factory = new DiskFileItemFactory();
// Create a new file upload handler
ServletFileUpload upload = new ServletFileUpload(factory);
// Parse the request
List<?> items = upload.parseRequest(request);
Iterator iter = items.iterator();
while (iter.hasNext()) {
FileItem item = (FileItem) iter.next();
if (item.isFormField()) {
// 如果是普通表单字段
String name = item.getFieldName();
String value = item.getString();
// ...
} else {
// 如果是文件字段
String fieldName = item.getFieldName();
String fileName = item.getName();
String contentType = item.getContentType();
boolean isInMemory = item.isInMemory();
long sizeInBytes = item.getSize();
String filePath="E:/"+fileName;
//写入文件到当前服务器磁盘
File uploadedFile = new File(filePath);
// File uploadedFile = new File("D:\haha.txt");
item.write(uploadedFile);
}
}
response.setCharacterEncoding("UTF-8");
response.getWriter().println("上传成功");
return null;
}
以上是文件接收服务端代码,确保http://ip:端口/controller层映射路径/receive可以进入方法
开始客户端上传
@RequestMapping("/testUploadImg1")
public String upload(HttpServletRequest request) throws Exception {
//File f = new File("C:/Users/N-385/Desktop/qita/bbbbbb.jpg");
InputStream uploadedStream=new FileInputStream (new File("C:/Users/N-385/Desktop/qita/aa.jpg"));
//上传到远程服务器
//InputStream uploadedStream = item.getInputStream();
String fileName="aa.jpg";//应该是从传进的multipartFile获取名字
HashMap<String, InputStream> files = new HashMap<String, InputStream>();
files.put(fileName, uploadedStream);
uploadToFarService(files);
uploadedStream.close();
return "redirect:/";//上传成功重定向到哪里
}
public void uploadToFarService(HashMap<String, InputStream> files) {
try {
String BOUNDARY = "---------7d4a6d158c9"; // 定义数据分隔线
URL url = new URL("http://ip:端口/imageUpload/receive");//对应上述接收文件映射路径
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/4.0 (compatible; MSIE 6.0; Windows NT 5.1; SV1)");
conn.setRequestProperty("Charsert", "UTF-8");
conn.setRequestProperty("Content-Type",
"multipart/form-data; boundary=" + BOUNDARY);
OutputStream out = new DataOutputStream(conn.getOutputStream());
byte[] end_data = ("\r\n--" + BOUNDARY + "--\r\n").getBytes();// 定义最后数据分隔线
Iterator iter = files.entrySet().iterator();
int i=0;
while (iter.hasNext()) {
i++;
Map.Entry entry = (Map.Entry) iter.next();
String key = (String) entry.getKey();
InputStream val = (InputStream) entry.getValue();
String fname = key;
File file = new File(fname);
StringBuilder sb = new StringBuilder();
sb.append("--");
sb.append(BOUNDARY);
sb.append("\r\n");
sb.append("Content-Disposition: form-data;name=\"file" + i
+ "\";filename=\"" + key + "\"\r\n");
sb.append("Content-Type:application/octet-stream\r\n\r\n");
byte[] data = sb.toString().getBytes();
out.write(data);
DataInputStream in = new DataInputStream(val);
int bytes = 0;
byte[] bufferOut = new byte[1024];
while ((bytes = in.read(bufferOut)) != -1) {
out.write(bufferOut, 0, bytes);
}
out.write("\r\n".getBytes()); // 多个文件时,二个文件之间加入这个
in.close();
}
out.write(end_data);
out.flush();
out.close();
// 定义BufferedReader输入流来读取URL的响应
BufferedReader reader = new BufferedReader(new InputStreamReader(
conn.getInputStream(), "UTF-8"));
String line = null;
while ((line = reader.readLine()) != null) {
System.out.println(line);
}
} catch (Exception e) {
System.out.println("发送POST请求出现异常!" + e);
e.printStackTrace();
}
}
此外还遇到了一个问题,接收文件的服务端
List<?> items = upload.parseRequest(request);
得到的结果为空,因为在配置文件中
<bean id="multipartResolver"
class="org.springframework.web.multipart.commons.CommonsMultipartResolver">
<property name="maxUploadSize" value="10485760" />
</bean>
最后把这里注释掉就可以了。