resteasy服务器代码

 @Path(value = "file")
public class UploadFileService {
private final String UPLOADED_FILE_PATH = "d:\\resteasy\\";
@POST
@Path(value = "/upload")
@Consumes("multipart/form-data")
public Response uploadFile(MultipartFormDataInput input) {
String fileName = "";
Map<String, List<InputPart>> uploadForm = input.getFormDataMap();
List<InputPart> inputParts = uploadForm.get("file_upload");
for (InputPart inputPart : inputParts) {
try {
MultivaluedMap<String, String> header = inputPart.getHeaders();
fileName = getFileName(header);
//convert the uploaded file to inputstream
InputStream inputStream = inputPart.getBody(InputStream.class,null);
byte [] bytes = IOUtils.toByteArray(inputStream);
//constructs upload file path
fileName = UPLOADED_FILE_PATH + fileName;
writeFile(bytes,fileName);
} catch (IOException e) {
e.printStackTrace();
}
}
return Response.status(200)
.entity("uploadFile is called, Uploaded file name : " + fileName).build();
} private String getFileName(MultivaluedMap<String, String> header) {
String[] contentDisposition = header.getFirst("Content-Disposition").split(";");
for (String filename : contentDisposition) {
if ((filename.trim().startsWith("filename"))) {
String[] name = filename.split("=");
String finalFileName = name[1].trim().replaceAll("\"", "");
return finalFileName;
}
}
return "unknown";
} //save to somewhere
private void writeFile(byte[] content, String filename) throws IOException {
File file = new File(filename);
if (!file.exists()) {
file.createNewFile();
}
FileOutputStream fop = new FileOutputStream(file);
fop.write(content);
fop.flush();
fop.close();
}
}

客户端代码

 <form action="http://localhost:8080/resteay-server/file/upload/"
method="post" enctype="multipart/form-data">
<input type="file" name="file_upload"> <input type="submit"
value="提交">
</form>
05-11 20:01