欢迎您访问程序员文章站本站旨在为大家提供分享程序员计算机编程知识!
您现在的位置是: 首页

resteasy实现文件上传

程序员文章站 2022-07-16 22:30:55
...

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>

 

相关标签: java resteasy