resteasy上传文件写法

resteasy服务器代码

 1 @Path(value = "file")
 2 public class UploadFileService {
 3     private final String UPLOADED_FILE_PATH = "d:\resteasy\";
 4     @POST
 5     @Path(value = "/upload")
 6     @Consumes("multipart/form-data")
 7     public Response uploadFile(MultipartFormDataInput input) {
 8         String fileName = "";
 9         Map<String, List<InputPart>> uploadForm = input.getFormDataMap();
10         List<InputPart> inputParts = uploadForm.get("file_upload");
11         for (InputPart inputPart : inputParts) {
12          try {
13             MultivaluedMap<String, String> header = inputPart.getHeaders();
14             fileName = getFileName(header);
15             //convert the uploaded file to inputstream
16             InputStream inputStream = inputPart.getBody(InputStream.class,null);
17             byte [] bytes = IOUtils.toByteArray(inputStream);
18             //constructs upload file path
19             fileName = UPLOADED_FILE_PATH + fileName;
20             writeFile(bytes,fileName);
21           } catch (IOException e) {
22             e.printStackTrace();
23           }
24         }
25         return Response.status(200)
26             .entity("uploadFile is called, Uploaded file name : " + fileName).build();
27     }
28  
29     private String getFileName(MultivaluedMap<String, String> header) {
30         String[] contentDisposition = header.getFirst("Content-Disposition").split(";");
31         for (String filename : contentDisposition) {
32             if ((filename.trim().startsWith("filename"))) {
33                 String[] name = filename.split("=");
34                 String finalFileName = name[1].trim().replaceAll(""", "");
35                 return finalFileName;
36             }
37         }
38         return "unknown";
39     }
40  
41     //save to somewhere
42     private void writeFile(byte[] content, String filename) throws IOException {
43         File file = new File(filename);
44         if (!file.exists()) {
45             file.createNewFile();
46         }
47         FileOutputStream fop = new FileOutputStream(file);
48         fop.write(content);
49         fop.flush();
50         fop.close();
51     }
52 }

 客户端代码

1 <form action="http://localhost:8080/resteay-server/file/upload/"
2         method="post" enctype="multipart/form-data">
3         <input type="file" name="file_upload"> <input type="submit"
4             value="提交">
5 </form>
原文地址:https://www.cnblogs.com/shamo89/p/7149114.html