java上传文件到远程服务器(一)---HttpURLConnection方式 3
- UID
- 1066743
|
java上传文件到远程服务器(一)---HttpURLConnection方式 3
服务端
我们仍然在基础项目上fileController中实现接收文件。代码如下:
FileController.java
package com.test.web.controller;
import java.io.File;
import java.util.Iterator;
import java.util.List;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import org.apache.commons.fileupload.FileItem;
import org.apache.commons.fileupload.disk.DiskFileItemFactory;
import org.apache.commons.fileupload.servlet.ServletFileUpload;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
/**
* IndexController
*
*
*/
@Controller
public class FileController {
//private static final String STORE_FILE_DIR="/usr/local/image/";//文件保存的路径
private static final String STORE_FILE_DIR="D:\\";//文件保存的路径
@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=STORE_FILE_DIR+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;
}
}
我们需要把服务端发布到 远程服务器上 使用tomcat等运行起来。
如果项目中有shiro拦截的话记得设置成 /receive = anon 。让接收文件的路由不被拦截。
然后运行客户端,选择文件就可以上传了。对安全有要求的,可以在客户端加一个key,服务器端接收到请求后验证key,没问题的话 再写入目录和文件。 |
|
|
|
|
|