1,接口是:是二进制流上传图片(可以多张)如果加上参数的话建议不要这样写,建议采用第三方jar包
@POST
@Path("uploadFile.do")
@Produces(MediaType.APPLICATION_JSON)
public String uploadFile(@Context HttpServletRequest request)
throws UnsupportedEncodingException {
final String SERVER_UPLOAD_LOCATION_FOLDER = request.getSession()
.getServletContext().getRealPath("/")
+ "";// 物理路径
String Virthfilename = "";// 虚拟路径
if (!new File(SERVER_UPLOAD_LOCATION_FOLDER).isDirectory())
new File(SERVER_UPLOAD_LOCATION_FOLDER).mkdirs();// 没有就创建
String userID = null;
String recordID = null;
String filename = null;
String filetype = null;
Float filesize = null;
Boolean flag = false;
FileItemFactory factory = new DiskFileItemFactory();
ServletFileUpload upload = new ServletFileUpload(factory);
List<FileItem> items = null;
try {
items = upload.parseRequest(request);
} catch (FileUploadException e) {
e.printStackTrace();
}
if (items != null) {
Iterator<FileItem> iter = items.iterator();
while (iter.hasNext()) {
FileItem item = iter.next();
if (!item.isFormField() && item.getSize() > 0) {
filename = processFileName(item.getName());// 获取文件名
filesize = (float) item.getSize();// 获取文件大小
if (filesize > file_size_max) {
res.add("status", 10099);
res.add("msg", "上传图片超过最大值");
res.add("data", "");
return res.toString();
}
int numb = filename.lastIndexOf(".");
filetype = filename.substring(numb + 1);// 获取文件格式
if (!(filetype.equals("jpg") || filetype.equals("png")
|| filetype.equals("jpeg") || filetype
.equals("gif"))) {
res.add("status", 10099);
res.add("msg", "只能上传jpg,png,jpeg,gif类型文件");
res.add("data", "");
return res.toString();
}
filename = IdGen.uuid() + "." + filetype;
try {
if (recordID.equals("") || userID.equals("")) {
res.add("status", 10099);
res.add("msg", "上传失败");
res.add("data", "");
return res.toString();
}
java.util.List<MobUser> userli = mobUserDao
.findById(userID);
if (userli.size() == 0) {
res.add("status", 10003);
res.add("msg", "用户不存在");
res.add("data", "");
return res.toString();
}
item.write(new File(SERVER_UPLOAD_LOCATION_FOLDER
+ filename));
} catch (Exception e) {
e.printStackTrace();
}
flag = true;
} else {
}
}
if (flag) {
res.add("status", 0);
res.add("msg", "上传成功");
res.add("data", "");
return res.toString();
} else {
res.add("status", 10099);
res.add("msg", "没有收到文件");
res.add("data", "");
return res.toString();
}
} else {
res.add("status", 10009);
res.add("msg", "上传失败");
res.add("data", "");
return res.toString();
}
}
2jsp测试页面为
<form action="" method="post" enctype="multipart/form-data">
<table>
<tr>
File:<input type="file" name="fileup" /><br>
<input name="file" type="file" accept="image/*" single name="file" data-dojo-attach-point="fileNode" data-dojo-attach-event="onchange: onFileLoad">
</tr>
<tr>
<td><INPUT type="submit" value="上传"></td>
</tr>
</table>
</form>